簡體   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