我正在尋找一種異步迭代陣列并更新變數并最終回傳此變數的方法。
export const test = async(
...
): Promise<number> => {
let highestAmount = 0;
for (const entry of entries) {
const check = async () => {
let amount = 0
try {
newAmount = await getAmount(entry);
} catch (e) {
return;
}
if (newAmount > amount ) {
highestAmount = newAmount;
}
}
check()
}
return highestAmount;
}
在這個當前狀態下,我只得到 0,因為函式不等待它的完成。有沒有辦法讓函式只在 for 內的所有行程都完成時才回傳?假設 getAmount(entry) 函式需要 1 秒才能完成,然后我必須等待 entry.length 秒。我試圖找到一種在 1 秒內執行此操作的方法,因此為每個條目異步呼叫 getAmount => 函式回傳最高數字
uj5u.com熱心網友回復:
假設該
getAmount(entry)功能需要 1 秒才能完成,然后我必須等待entries.length幾秒鐘。我正在嘗試找到一種在 1 秒內執行此操作的方法
如果您有五個需要一秒鐘的呼叫,則您無法在一秒鐘內執行并從函式回傳值。
有沒有一種方法只有在 for 中的所有行程都完成時才回傳該函式?
是的。然而,這是可能的。
如果你map在你的陣列上生成一個你可以使用的 Promise 陣列,那么await你Promise.all可以使用Math.max從該陣列中獲取最大的數字。
// Generate a random number
function rnd() {
return Math.floor(Math.random() * (100 - 0) 0);
}
// Mock API call which returns the number passed into
// multiplied by an erratic method of
// creating a new random number
function getAmount(el) {
return new Promise(res => {
setTimeout(() => res((el - rnd()) rnd()), 500);
});
}
// Create an array of promises, await them to resolve
// and then return the highest number
async function getHighest(entries) {
const promises = entries.map(el => getAmount(el));
const data = await Promise.all(promises);
console.log(data);
return Math.max(...data);
}
// Await the promise that `getData` returns
// and log the result
async function main(entries) {
console.log(await getHighest(entries));
}
const entries = [1, 2, 3, 4, 5];
main(entries);
uj5u.com熱心網友回復:
有幾件事要讓這個等待:
- 在父函式中放置一個異步
- 在檢查函式呼叫中放置一個等待
例如:
export const test = async (
...
): Promise<number> => {
//...
await check();
};
也可能有一些方法可以讓這些異步呼叫并行運行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/468494.html
標籤:javascript 打字稿 异步
