Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript Promise.all returns last promise only

I have a script like:

var a = [{'a': 1},{'b': 2}]
var allPromises = new Array(a.length)
for(var i in a) {
    allPromises[i] = Promise.resolve().then(response => {
      console.log(i)
      console.log(a[i])
      // Do somethig on every loop with key and value
      return i
    })
}

Promise.all(allPromises).then(response => console.log(response))

Here in my for loop it only gives me last index and value of last index while I want the value on every loop and perform some action with key and value.. But I am getting the last key and value only..

I tried getting the value on Promise.all's response but didnt work.

How can I get the index of my array on allPromises's response ?

I can do it by makeing a counter. But when I again call the function the counter is reset so I donnt want to use the counter.

Is there anyway I can get index on every loop for promise ?

like image 604
gamer Avatar asked Jul 27 '16 07:07

gamer


1 Answers

Your i variable in the .then() handler inside your for loop isn't what you think it is. Your for loop has already run to completion before any of your .then() handlers get called (since they always run asynchronously on a future tick). Thus, you only think you're seeing the last promise, but actually all the promises are working fine, it's just that they are all returning the last value of i.

You can fix it by using .forEach() to iterate your array because it uniquely captures each value of i.

var a = [{'a': 1},{'b': 2}]
var allPromises = new Array(a.length);
a.forEach(function(item, i) {
     allPromises[i] = Promise.resolve().then(response => {
      console.log(i)
      console.log(a[i])
      // Do somethig on every loop with key and value
      return i
    })
});

Promise.all(allPromises).then(response => console.log(response))

Or, since you're generating an array as a result, you could use .map():

var a = [{'a': 1},{'b': 2}]
var allPromises = a.map(function(item, i) {
  return Promise.resolve().then(response => {
    console.log(i)
    console.log(a[i])
    // Do somethig on every loop with key and value
    return i
  })
});

Promise.all(allPromises).then(response => console.log(response))
like image 98
jfriend00 Avatar answered Oct 23 '22 10:10

jfriend00