gpt4 book ai didi

javascript - 在 Javascript 数组映射中使用 promise 函数

转载 作者:IT王子 更新时间:2023-10-29 03:04:57 25 4
gpt4 key购买 nike

有一个对象数组 [obj1, obj2]

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

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

当然这是行不通的,输出数组是[undefined, undefined]

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

最佳答案

将您的数组映射到 promises,然后您可以使用 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)
})

关于javascript - 在 Javascript 数组映射中使用 promise 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39452083/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com