簡體   English   中英

異步迭代數組元素

[英]Iterating over array elements asynchronously

我正在嘗試對數組元素列表進行異步迭代,但是使用以下代碼:

const calculate = async ({ id, priority, database, product }) => {
    let list_of_products;
    if (priority) {
        list_of_products = await getPriorityList(database, id);
    }
    else {
        const prods = product.split(',');
        await prods.forEach((prod) => {
            list_of_products = getList(database, prod);
            console.log({ list_of_products });
        });
    }
};

我得到以下console.log()

{ list_of_products : Promise { <pending> } }

當然,最終會引發錯誤。

迭代時處理異步調用的最佳實踐是什么? getList()方法也是異步的。

不要在 forEach 循環中使用異步等待。 await prods.forEach((prod) 。代替forEach循環,您可以使用for...of循環。檢查一下: Using async/await with a forEach loop

您需要在getList(database, prod)前面添加await關鍵字。 否則,異步 function 將返回 promise。

我重構了你的代碼。

const calculate = async ({ id, priority, database, product }) => {
    let list_of_products;
    if (priority) {
        list_of_products = await getPriorityList(database, id);
    }
    else {
        const prods = product.split(',');
        for(let prod of prods) {
            list_of_products = await getList(database, prod);
            console.log({ list_of_products });
        }
    }
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM