繁体   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