我有下面的代碼,它使用 api 來獲取客戶資料。問題是當回圈轉到第二個索引時,它customerIds確實保留了前一個索引的值index(參見下面的控制臺日志)。
有人知道如何正確實作這一目標嗎?
這是我的代碼
let customerIds = [];
arrayChunks.forEach(async (chunkGroupIds, index) => {
try {
console.log('customerIds - before', index, customerIds)
const checkStatusResult = await checkStatus(
token,
chunkGroupIds
)
chunkGroupIds.map((customerId) => {
const found = checkStatusResult.response.data.find(
(data) => customerId.toString() === data.customerId
)
if (found) {
customerIds = [...customerIds, customerId]
}
})
console.log('customerIds - after', index, customerIds)
} catch (error) {
...
}
})
console.log('customerIds - final', customerIds)
控制臺日志:問題可以通過正在列印的文本來顯示。正如我們所看到的,當它進入第二個索引時,它沒有從索引一個獲得前一個值。
customerIds - before 0 []
customerIds - after 0 [2,3,5]
customerIds - before 1 []
customerIds - after 1 []
... and so on
customerIds - final []
uj5u.com熱心網友回復:
使用for of回圈而不是回呼方法
let customerIds = [];
let index = 0;
for (const chunkGroupIds of arrayChunks) {
try {
console.log('customerIds - before', index, customerIds)
const checkStatusResult = await checkStatus(
token,
chunkGroupIds
)
chunkGroupIds.map((customerId) => {
const found = checkStatusResult.response.data.find(
(data) => customerId.toString() === data.customerId
)
if (found) {
customerIds.push(customerId);
}
})
console.log('customerIds - after', index, customerIds)
} catch (error) {
...
} finally {
index ;
}
}
console.log('customerIds - final', customerIds)
uj5u.com熱心網友回復:
這似乎是一個異步問題,它可能看起來像陣列中的承諾按順序運行,但事實并非如此。在forEach回圈中,所有這些都同時運行。
在您的情況下,這可能是件好事,因為您不必等待順序時間的總和,您可能正在苦苦掙扎的最后部分是您希望查看包含所有附加值的最終陣列,為此我推薦以下內容:
const promises = arrayChunks.map(async (chunkGroupIds, index) => {
try {
console.log('customerIds - before', index, customerIds)
const checkStatusResult = await checkStatus(
token,
chunkGroupIds
)
chunkGroupIds.map((customerId) => {
const found = checkStatusResult.response.data.find(
(data) => customerId.toString() === data.customerId
)
if (found) {
customerIds = [...customerIds, customerId]
}
})
console.log('customerIds - after', index, customerIds)
} catch (error) {
...
}
})
await Promise.all(promises); // Wait until all of them are finished
console.log('customerIds - final', customerIds)
在這里,該Promise.all實用程式允許您等到一組 Promise 完成,由于async關鍵字,函式會自動映射到 Promise。
如果您需要按順序執行您的承諾,您可以使用@amir-saleem 推薦的方法。否則,我的建議在性能方面會更好。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/445678.html
標籤:javascript 异步 异步等待
