3 回答

TA貢獻1801條經(jīng)驗 獲得超16個贊
首先,您需要在運行之前等待所有承諾完成 res.json(...)
其次,您不應(yīng)該在承諾解析后改變外部變量(承諾解析的順序?qū)⒏淖兡妮敵?,這并不好。
像這樣的東西應(yīng)該可以正常工作
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, ....}
]) ]
*/

TA貢獻1842條經(jīng)驗 獲得超21個贊
作為替代答案,以下是您如何針對此特定查詢對數(shù)據(jù)庫進行 1 次旅行,這意味著您無需等待多個 Promise 并減少數(shù)據(jù)庫的負(fù)載
knex.raw(
'select name from users where user_id in (' + userId.map(_ => '?').join(',') + ')',
[...userId]
);
添加回答
舉報