简体   繁体   English

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

[英]Using promise function inside Javascript Array map

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

Map your array to promises and then you can use Promise.all() function:将您的数组映射到 Promise,然后您可以使用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)
})

You are not returning your Promises inside the map function.您没有在map函数中返回您的 Promises。

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

Example using async/await:使用异步/等待的示例:

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

您也可以for await代替map ,并在其中解决您的承诺。

You can also use p-map library to handle promises in map function.您还可以使用p-map 库来处理 map 函数中的 Promise。

Useful when you need to run promise-returning & async functions multiple times with different inputs concurrently.当您需要同时使用不同的输入多次运行 promise-returning 和 async 函数时很有用。

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.这与 Promise.all() 的不同之处在于您可以控制并发并决定是否在出现错误时停止迭代。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM