繁体   English   中英

无法弄清楚如何等待Promise

[英]Cannot figure out how to wait for Promise

我有一个带有用户ID的数组,我需要找出每个ID所属的名称并将其返回到数组中。 我可以使用knex从数据库中获取用户名并将其推送到数组中,但是当我尝试发送数据时,它始终是一个空数组。

我对Promises的态度不是很好,因此无法弄清楚如何将其应用于我的项目。

const userId = [10,11,12,13]
let users = []

userId.map(id => {
    db.select('name').from('users').where('user_id', id)
    .then(user => {
        users.push(user)
    })
})
res.json(users)

我希望响应能够等到循环结束并发送用户数组。

您的map正在创建一个undefined的数组,因为您的回调函数不返回任何内容。 如果我们稍作调整,它将创建一系列的Promise.all ,这正是Promise.all期望的。 :-)所以:

const userId = [10,11,12,13]
Promise.all(
    userId.map(id => db.select('name').from('users').where('user_id', id))
)
.then(users => {    // `users` is an array of users, in the same order as the IDs
    res.json(users);
})
.catch(error => {
    // Render an error response
});

首先,您需要先等待所有诺言完成,然后再运行res.json(...)

其次,您不应在诺维解析后对外部变量进行突变(诺维解析的顺序将改变您的输出,这并不好。

这样的事情应该可以正常工作

const userId = [10,11,12,13]

// map userId array to promise array
// Promise.all aggregates a promise array into one big promise that resolves when all promises resolve (and preserves array order)
Promise.all(
  userId.map(id =>
    db
      .select("name")
      .from("users")
      .where("user_id", id)
  )
)
  .then(users => res.json(users))
  .catch(e => console.error("Error::", e));

/*handle error in the catch block*/

/* visual example of Promise.all.then block
Promise.all([           users = [
   getUser(10),    ->     {userId: 10, ....}
   getUser(11),    ->     {userId: 11, ....}
   getUser(12)     ->     {userId: 12, ....}
])                      ]

*/

作为替代答案,这是针对这种特定查询的数据库访问方式,这意味着您无需等待多个Promises并减少数据库负载

knex.raw(
  'select name from users where user_id in (' + userId.map(_ => '?').join(',') + ')', 
  [...userId]
);

您需要Promise.all() ,请参见此处

尝试

const userId = [10,11,12,13]

let users = userId.map(id => new Promise(resolve => {
    db.select('name').from('users').where('user_id', id)
    .then(user => {
        resolve(user)
    })
}))
Promise.all(users).then(()=>res.json(users))

users在这里有很多承诺。 解决所有问题后,立即执行res.json(users)

暂无
暂无

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

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