等待地图结束后再继续

The*_* xd 1 javascript asynchronous node.js async-await

  let shouldHavePaid = 0;

  demographicsArray.map((country) => {
    if (country.checked == true) {
      Price.findOne({ country: country._id }).then((priceRes) => {
        if (priceRes) {
          shouldHavePaid = shouldHavePaid + priceRes.priceSMS * country.count;
        } else {
          shouldHavePaid = shouldHavePaid + 0.1 * country.count; //Default price for unlisted countries
        }
      });
    }
  });

  console.log(`Finish: ${shouldHavePaid}`);
Run Code Online (Sandbox Code Playgroud)

我希望最后的 console.log 在地图之后执行,但它在地图完成之前触发。我期待这个输出,因为据我所知地图应该是同步的而不是异步的。我相信对数据库的请求搞砸了?你在这里有什么建议?

mou*_*ail 5

您可以Promise.all与await结合使用:

await Promise.all(demographicsArray.map(async (...)=>{
    if (...) {
        await Prize... 
        if (priceRes) {
            ....
        }
    }
})

console.log(...)
Run Code Online (Sandbox Code Playgroud)

Await 可以在函数中使用,async仅在 Promise 完成后才运行下一行。Promise.all()允许你等待一系列的承诺。将回调标记为async使其返回一个可供Promise.all(). 它还允许您在函数内使用await,这样您就不必使用.then().