1

I am trying to console.log() after a forEach function using Async/Await or Callback(). But neither of them seems to be working. Here is the set of functions I am trying to execute.

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

I have even tried using ".map". It would be great if someone can tell me how can I achieve a async execution using Async/Await or Callback but by NOT using timeout.

codifier77
  • 21
  • 5

1 Answers1

0

In this case you can't use forEach because it doesn't work as you expect, instead, you can use for of in this way:


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);
Oscar Velandia
  • 1,157
  • 1
  • 7
  • 9