1

I'm trying to access array from out of loop but it seems somethings wrong. What did I miss out on? How should i do that?

funcA(){
  return new Promise((resp, rej) => {
    var list = [1,2,3,4,5];
    var array = [];
    list.forEach(i => {
      funcB(i).then(num => {
        array.push(num);
        console.log(array) //=> [1,2,3,4,5]
      })
    });
    console.log(array) //=> []
    resp(array) //=> []
  })
}

funcB(i){
  return new Promise((resp, rej) => { 
    resp(i);
  })
}
Zafer
  • 836
  • 7
  • 4
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – str Dec 18 '17 at 08:55
  • 2
    `funcB` is async. So, you need to wait (hint: `Promise.all`) for the all the promises of `funcB` and *then* do `resp(array)`. – Davin Tryon Dec 18 '17 at 08:55
  • Possible duplicate of [How to wait for function's promise in JavaScript](https://stackoverflow.com/questions/47773824/how-to-wait-for-functions-promise-in-javascript) – Stamos Dec 18 '17 at 08:59

2 Answers2

1

you can do something like this.

function funcA(){

  var list = [1,2,3,4,5];
  return Promise.all( 
    list.map(val => {
      return funcB(val)
    })
  )
   
}

function funcB(i){
  return new Promise((resp, rej) => { 
    resp(i);
  })
}

funcA().then(arr => console.log(arr))
Amit Wagner
  • 3,134
  • 3
  • 19
  • 35
1

As you are calling an asynchronous function into the loop, you need to wait until all the calls are executed to access the array:

funcA(){
  return new Promise((resp, rej) => {
    var list = [1,2,3,4,5];
    var promisesArray = [];
    list.forEach(i => {
      promisesArray.push(funcB(i));
    });
    resp(Promises.all(promisesArray));
  });
}
David Vicente
  • 3,091
  • 1
  • 17
  • 27