在Javascript数组映射中使用Promise函数 [英] Using promise function inside Javascript Array map
本文介绍了在Javascript数组映射中使用Promise函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
具有对象[obj1,obj2]的数组
Having an array of objects [obj1, obj2]
我想使用Map函数对所有它们进行数据库查询(使用promise)并将查询结果附加到每个对象.
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
})
})
当然这是行不通的,输出数组是[undefined,undefined]
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
推荐答案
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)
})
这篇关于在Javascript数组映射中使用Promise函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文