3 回答
![?](http://img1.sycdn.imooc.com/54584f240001db0a02200220-100-100.jpg)
TA贡献1801条经验 获得超16个赞
首先,您需要在运行之前等待所有承诺完成 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, ....}
]) ]
*/
![?](http://img1.sycdn.imooc.com/533e4d470001a00a02000200-100-100.jpg)
TA贡献1842条经验 获得超21个赞
作为替代答案,以下是您如何针对此特定查询对数据库进行 1 次旅行,这意味着您无需等待多个 Promise 并减少数据库的负载
knex.raw(
'select name from users where user_id in (' + userId.map(_ => '?').join(',') + ')',
[...userId]
);
添加回答
举报