0

So i got this

for(var i =0;i<result.length;i++){
    User.find(result[i].user).then((err,user)=>{
        resultArray.push({name : result[i].name, userName : user.name});     
    }
}

but it doesn't work because the loops end before the promises resolves. So i wanted to know if i could give a copy of i to the User.find() callback? I don't know any way to keep the data synced between the result and user array, since i don't know in which order the promises are gonna be resolved.

  • `result.forEach(res=> User.find(res.user).then(...` – wbadart Jul 15 '17 at 01:26
  • Okay but, how can i know that every request has been completed? – Killian Allegrain Jul 15 '17 at 01:30
  • @KillianAllegrain for these sorts of things you may want to consider using something like [async](https://github.com/caolan/async) or Promise.all – aug Jul 15 '17 at 01:33
  • @KillianAllegrain it doesn't tell you when the promise returns, but with the `forEach` method, you're getting a copy of the array elements, and aren't relying on a constantly changing index (`i`) to access the result array – wbadart Jul 15 '17 at 01:33
  • Just leave it open ;) Maybe someone else will stumble upon your question – lumio Jul 15 '17 at 01:41

1 Answers1

0

Mentioned in the comments section, you want to resolve all users. You can use the Array method map to generate an Array of Promises to then pass to Promise.all, like so:

Promise.all(
  result.map( res => User.find( ... ) )
)
  .then( result => {
    // all resolved users are in result
  } );
lumio
  • 7,428
  • 4
  • 40
  • 56