在 Javascript Array 映射中使用承诺函数

有一个对象数组[ objec1,objec2]的

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

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

当然这不起作用,并且输出数组是[ unDefinition,unDefinition ]

解决这类问题的最好方法是什么? 我不介意使用其他类库,比如异步

118220 次浏览

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

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

You can also do for await instead of map, and resolve your promises inside of it as well.

Example using async/await:

const mappedArray = await Promise.all(
array.map(p => {
return getPromise(p).then(i => i.Item);
})
);

You can also use p-map library to handle promises in map function.

Useful when you need to run promise-returning & async functions multiple times with different inputs concurrently.

This is different from Promise.all() in that you can control the concurrency and also decide whether or not to stop iterating when there's an error.