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);
  })
}
3

2 Answers 2

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))

Sign up to request clarification or add additional context in comments.

Comments

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));
  });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.