102

Having an array of objects [obj1, obj2]

I want to use Map function to make a DB query (that uses promises) about all of them and attach the results of the query to each object.

[obj1, obj2].map(function(obj){
  db.query('obj1.id').then(function(results){
     obj1.rows = results
     return obj1
  })
})

Of course this doesn't work and the output array is [undefined, undefined]

What's the best way of solving a problem like this? I don't mind using other libraries like async

1
  • 14
    This question should not have been marked as a duplicate. This question is specifically about using promises inside map, not how does async work in general. Commented Feb 22, 2018 at 15:41

5 Answers 5

214

Map your array to promises and then you can use Promise.all() function:

var promises = [obj1, obj2].map(function(obj){
  return db.query('obj1.id').then(function(results){
     obj1.rows = results
     return obj1
  })
})
Promise.all(promises).then(function(results) {
    console.log(results)
})
Sign up to request clarification or add additional context in comments.

2 Comments

how can i match results of promises and data from original model in this case? I want to combine them in starting model
the order in the arrays is perserved, so you can use array index to match the data and results
22

Example using async/await:

const mappedArray = await Promise.all(
  array.map(p => {
    return getPromise(p).then(i => i.Item);
  })
);

2 Comments

Is await necessary here? I thought Promise.all already awaits all promises.
Promise.all returns a promise that resolves when all promises resolve, otherwise it fails
16

You are not returning your Promises inside the map function.

[obj1, obj2].map(function(obj){
  return db.query('obj1.id').then(function(results){
     obj1.rows = results
     return obj1
  })
})

Comments

9

You can also do for await instead of map, and resolve your promises inside of it as well.

4 Comments

my preferred way to go
Could you give an example of this?
You can also do for await instead of map, and resolve your promises inside of it as well. Great! How would I do that?
-1

You can also use p-map library to handle promises in map function.

Useful when you need to run promise-returning & async functions multiple times with different inputs concurrently.

This is different from Promise.all() in that you can control the concurrency and also decide whether or not to stop iterating when there's an error.

2 Comments

There is also a more generic iter-ops module that has waitRace operator to do the same.
it is not necessary to use library to this task

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.