【问题标题】:Get Sync Trouble in ForEach在 ForEach 中遇到同步问题
【发布时间】:2019-10-22 12:17:49
【问题描述】:

我用这个功能

        await getTestData(entry).then(res=> {
            for(let i = 0; i < res.length; i++){
                //console.log(res[0].data)
                console.log("line");
            }

        }).catch(error => {
            console.log("MongoGetError");
        });
  console.log("end");

结果是

  1. 结束

现在我必须将其放入 .forEach() 循环中。我试过了:

    testcases.forEach(async function(entry,index) {


        await getTestData(entry).then(res=> {
            for(let i = 0; i < res.length; i++){
                //console.log(res[0].data)
                console.log("line");
            }

        }).catch(error => {
            console.log("MongoGetError");
        });

    });

    console.log("End");

但结果是:

  1. 结束

我到底错在哪里

  1. 结束

【问题讨论】:

  • 您可以尝试使用map 而不是forEach,然后将整个testcases.forEach(...) 包裹在Promise.all(...).then(() =&gt; console.log("End")) 中。目前,您的 console.log("End") 将首先执行,因为没有任何东西等待异步 forEach 完成。很快,您可能会尝试 allSettled 而不是 all,如果其中一个迭代失败,它也不会失败。

标签: node.js async-await synchronization


【解决方案1】:

注意——你已经在一个返回类似 map(); 的方法中进行了迭代。 forEach() 不返回任何内容
第 1 步 - 将 map() 放入 promise.all() 方法
第 2 步 - 您必须通过 await.then() 或任何其他子进程

持有 promise.all()

【讨论】:

    猜你喜欢
    • 2016-06-28
    • 1970-01-01
    • 2013-12-10
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 2020-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多