0

I'm working on a nodeJS script and I would like to know how to execute a function after an another one. Because actually i need to save in my database some data and then retrieve them. However for the moment my retrieve is executed before my save :/ Have already looked on internet there is a lot of example I tried them but for the moment no one worked ... I should probably do something wrong if somebody could help me on it :)

function persistMAP(jsonData, callback) {
  console.log(jsonData);
  //Deck persistance
  for (var i = 0; i < 1; i++) {
    (function(i) {
      var rowData = new DeckDatabase({
        _id: new mongoose.Types.ObjectId(),
        DeckNumber: Number(jsonData.Deck[i].DeckNumber),
        x: Number(jsonData.Deck[i].x),
        y: Number(jsonData.Deck[i].y),
      });
      rowData.save(function(err) {
        if (err) return console.log(err);

        for (var i = 0; j = jsonData.Units.length, i < j; i++) {
          (function(i) {
            var unit = new MapDatabase({
              //UnitID:  mongoose.ObjectId(jsonData.Units[i].UnitID),
              UnitID: jsonData.Units[i].UnitID,
              TypeID: Number(jsonData.Units[i].TypeID),
              x: Number(jsonData.Units[i].x),
              y: Number(jsonData.Units[i].y),
              _id: mongoose.Types.ObjectId(jsonData.Units[i].Code + 'dd40c86762e0fb12000003'),
              MainClass: jsonData.Units[i].MainClass,
              Orientation: jsonData.Units[i].Orientation,
              Postion: jsonData.Units[i].Postion,
              Deck: String(rowData._id)
            });

            unit.save(function(err) {
              if (err) return console.log(err);
              console.log('save');
            });
          })(i);
        }

      });

    })(i);
  }
  callback();
}; 



app.get("/Map", function(req, res) {
  console.log("got");

  var urlTempBox = 'http://localhost:3000/MapCreate';
  DeckDatabase.find(null, function(err, data) {
    if (err) {
      throw (err);
    }
    if (data.length != 0) {
      MapDatabase.find()
        .populate('Deck')
        .exec(function(err, finalData) {
        res.send(finalData);
      });
    } else {
      request(urlTempBox, data, function(error, response, body) {
        if (error) {
          throw (error);
        } else {
          var jobj = JSON.parse(response.body);
          console.log("persist begin");
          persistMAP(jobj, function() {
            console.log('retrieve Done');
          });
        }
      });
    }
  });
Manish Balodia
  • 1,863
  • 2
  • 23
  • 37
Chris
  • 41
  • 6
  • Please read [What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation) – str Jul 30 '18 at 12:34
  • Possible duplicate of [What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation) – Akhilesh Awasthi Jul 30 '18 at 12:54

1 Answers1

0

You can use javascript callbacks like this:

User.findById(user_id,function(err,data){
  //Inside this you can call another function.

});

console.log("Hello"); //this statement won't wait for the above statement 

The more good approach would be use promises.

You can also use async await function to handle asynchronus tasks.

Async Await Style

   async function getData(){
    let user_data=await User.findById(user_id);
    let user_videos=await Videos.findById(user_data._id);  //user_data._id is coming from the above statement
    }

But you can only use await in async methods. Hope it helps.

Zeeshan Tariq
  • 604
  • 5
  • 10
  • maybe with promise yes but how should I say that my persistence is done to my promise's resolve method – Chris Jul 30 '18 at 13:02