what is the order in which node js runs this code?

58 Views Asked by At

I am working with Node.js module AR-Drone to control my parrot ar. drone 2.0. and I am using this structure.

client.takeoff();
client.after(5000, function () {
  this.on("navdata", function (d) {
    if (d.demo) {
      //totaly and totalx are calculated here using navdata
      if (totaly > 85) {
        // if the deviation is far to the right more than 85 mm
        console.log("moving left ");
        client.left(0.15);
        sleep(500).then(() => {
          client.stop();
        });
      } else if (totaly < -85) {
        // if the deviation is far to the left more than 85 mm
        console.log("                          moving right");
        client.right(0.15);
        sleep(500).then(() => {
          client.stop();
        });
      } else if (totalx < 3000) {
        client.front(0.02);
        sleep(250).then(() => {
          client.stop();
        });
        console.log("moving forward");
      } else {
        client.land();
      }
    }
  });
});

My question is that when I write sleep(500) and then do something, does the program actualy wait 500 ms or the "if cycles" run at the same time? what is the order of the actions sent to the drone?

1

There are 1 best solutions below

2
Tsvetan Ganev On

The sleep function does not block the thread for the duration but instead schedules the callback to run right after the time has passed. However, the code outside of the callback runs synchronously.

client.front(0.02); // this runs first
sleep(250).then(() => {
  // this runs third (after 250ms)
  client.stop();
});
console.log("moving forward"); // this runs second

So, if you want a guarantee that something runs "after the sleep", you have to put it inside the .then() callback or use async/await.

Example with async/await:

async function run() {
  await sleep(500);
  // everything below is guaranteed to run after the "sleep"
  console.log('500 ms have passed')
}
run();