Zafer
Zafer

Reputation: 826

node.js function returns empty

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

Upvotes: 1

Views: 53

Answers (2)

David Vicente
David Vicente

Reputation: 3111

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

Upvotes: 1

Amit Wagner
Amit Wagner

Reputation: 3264

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

Upvotes: 1

Related Questions