简体   繁体   English

异步迭代数组元素

[英]Iterating over array elements asynchronously

I'm trying to iterate asynchronously over list of array elements, but with this code:我正在尝试对数组元素列表进行异步迭代,但是使用以下代码:

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 });
        });
    }
};

I get the following console.log() :我得到以下console.log()

{ list_of_products : Promise { <pending> } }

And of course, an error gets thrown eventually.当然,最终会引发错误。

What is the best practice to handle async calls when iterating?迭代时处理异步调用的最佳实践是什么? The getList() method is async as well. getList()方法也是异步的。

do not use async await in forEach loops.不要在 forEach 循环中使用异步等待。 await prods.forEach((prod) . instead of forEach loop you can use for...of loop. checkout this: Using async/await with a forEach loop await prods.forEach((prod) 。代替forEach循环,您可以使用for...of循环。检查一下: Using async/await with a forEach loop

you need to add await keyword in front of your getList(database, prod) .您需要在getList(database, prod)前面添加await关键字。 otherwise, that async function will return a promise.否则,异步 function 将返回 promise。

I refactored your code.我重构了你的代码。

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