在Javascript Array map中使用promise函数

Jor*_*rge 48 javascript arrays promise

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

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

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

当然这不起作用,输出数组是[undefined,undefined]

解决这类问题的最佳方法是什么?我不介意使用像async这样的其他库

mad*_*ox2 116

将数组映射到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)
})
Run Code Online (Sandbox Code Playgroud)


fed*_*608 21

使用异步/等待的示例:

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


mdz*_*kon 10

你没有在map函数中返回你的Promises .

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


小智 9

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