'Using promise function inside Javascript Array map

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



Solution 1:[1]

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

Solution 2:[2]

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

Solution 3:[3]

Example using async/await:

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

Solution 4:[4]

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

Solution 5:[5]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 madox2
Solution 2 mdziekon
Solution 3 fede1608
Solution 4 Pedro Paes
Solution 5 Jakub Kurdziel