Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 702
Jorge Avatar asked Sep 12 '16 13:09

Jorge


2 Answers

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)
})
like image 138
madox2 Avatar answered Oct 17 '22 22:10

madox2


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
  })
})
like image 16
mdziekon Avatar answered Oct 17 '22 20:10

mdziekon