在 Javascript Array 映射中使用 promise 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39452083/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:34:30  来源:igfitidea点击:

Using promise function inside Javascript Array map

javascriptarrayspromise

提问by Jorge

Having an array of objects [obj1, obj2]

有一个对象数组 [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.

我想使用 Map 函数对所有对象进行数据库查询(使用承诺)并将查询结果附加到每个对象。

[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]

当然这不起作用,输出数组是 [undefined, undefined]

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

解决此类问题的最佳方法是什么?我不介意使用其他库,比如 async

回答by madox2

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

将您的数组映射到承诺,然后您可以使用Promise.all()函数:

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

回答by mdziekon

You are not returning your Promises inside the mapfunction.

你没有在map函数内返回你的承诺。

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