美文网首页
await不能用于foreach的解决方案

await不能用于foreach的解决方案

作者: 周星星的学习笔记 | 来源:发表于2021-03-30 17:42 被阅读0次

    今天在做一个模拟队列任务执行的功能的时候,发现使用await不能使用foreach,后来发现使用for...of或者for语句就能解决这个问题。

    一、使用forEach的代码

    let func = (num) => {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve('执行数据' + num)
            }, 1000);
        })
    }
    
    async function test() {
        [1, 2, 3, 4, 5, 6, 7].forEach((item, index) => {
            let ret = await func(item);
            console.log(ret);
        });
    }
    test();
    
    结果

    二、使用for...of或者for语句

    let func = (num) => {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve('执行数据' + num)
            }, 1000);
        })
    }
    async function test() {
        //for...of
        for (const item of [1, 2, 3, 4, 5, 6, 7]) {
            let ret = await func(item);
            console.log(ret);
        }
        //for
        for (let index = 0; index < [1, 2, 3, 4, 5, 6, 7].length; index++) {
            let ret = await func(index);
            console.log(ret);
        }
    }
    test();
    
    结果

    相关文章

      网友评论

          本文标题:await不能用于foreach的解决方案

          本文链接:https://www.haomeiwen.com/subject/jbughltx.html