在 Javascript Array 映射中使用 promise 函数 [英] Using promise function inside Javascript Array map
本文介绍了在 Javascript Array 映射中使用 promise 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有一个对象数组 [obj1, obj2]
Having an array of objects [obj1, obj2]
我想使用 Map 函数对所有这些对象进行数据库查询(使用承诺),并将查询结果附加到每个对象.
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]
解决此类问题的最佳方法是什么?我不介意使用其他库,比如 async
What's the best way of solving a problem like this? I don't mind using other libraries like async
推荐答案
将你的数组映射到 promises,然后你就可以使用 Promise.all() 函数:
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 Array 映射中使用 promise 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文