【问题标题】:Function after forEach execution [duplicate]forEach 执行后的功能
【发布时间】:2020-04-25 21:50:31
【问题描述】:

我正在使用 Async/Await 或 Callback() 在 forEach 函数之后尝试 console.log()。但他们似乎都没有工作。这是我要执行的一组函数。

addAirports = async(airportsJson, callBack) => {
    await airportsJson.forEach( async(airport) => {        
        let db_find = await airportsModel.find({iata_code: airport.iata_code});
        if (db_find[0] == null) {
            airportsModel.insertMany(airport, function(error, docs) {});
            console.log(airport)
        }
    });
    callBack()
};

airportsUpdated = () => {
    console.log("All airports are updated")
}

addAirports(airportsInput, airportsUpdated);

我什至尝试过使用“.map”。如果有人能告诉我如何使用 Async/Await 或 Callback 但不使用超时来实现异步执行,那就太好了。

【问题讨论】:

  • forEach 不等待它的回调。 await airportsJson.forEach 不会做你认为的事情。
  • 我也试过“地图”
  • 同样的事情。另一种选择是,例如成为for (airport of airportsJson) { /*...*/ }
  • 那行得通,您能否将其发布为答案,因为没有其他类似的问题可以像您一样直接回答:)。
  • 这能回答你的问题吗? Using async/await with a forEach loop

标签: javascript node.js asynchronous foreach


【解决方案1】:

在这种情况下,您不能使用 forEach,因为它无法按预期工作,相反,您可以通过这种方式使用 for of


addAirports = async (airportsJson, callBack) => {
  for (const airports of airportsJson) {
    let db_find = await airportsModel.find({ iata_code: airport.iata_code });
    if (db_find[0] == null) {
      airportsModel.insertMany(airport, function (error, docs) {});
      console.log(airport);
    }
  }

  callBack();
};

airportsUpdated = () => {
  console.log("All airports are updated");
};

addAirports(airportsInput, airportsUpdated);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-17
    • 1970-01-01
    相关资源
    最近更新 更多