DEV Community

Discussion on: Async programming basics every JS developer should know

Collapse
 
siwalikm profile image
Siwalik Mukherjee • Edited

Hi Alwyn, the examples are asynchronously executed indeed, just that for the simplicity's sake our example level functions call the callbacks instantly. I have not introduced a setTimeout or a ajax call inside the functions but you can play around and see that even if you do, they work perfectly.

Here's an example demonstrating that

function levelOne(value, callback) {
  var newScore = value + 5;
  // making API call to slower server with 5 sec. delay
  fetch('https://www.mocky.io/v2/5b5c746332000081004262fd?mocky-delay=5000ms')
    .then(function (response) {
      return response.json();
    })
    .then(function (myJson) {
      console.log(`// delay on async api call for ${myJson.delay}`);
      callback(newScore);
    });
  // p.s. although setTimeout makes your code behave like async(), it is not.
  // read more => https://softwareengineering.stackexchange.com/q/194580/
}

function startGame() {
  var currentScore = 5;
  console.log(`Game Started! Current score is ${currentScore}`);
  levelOne(currentScore, function (levelOneReturnedValue) {
    console.log(`Level One reached! New score is ${levelOneReturnedValue}`);
  });
  console.log(`Hi, I'm a rebel and I don't wait for levelOne`);
}

startGame();

// Game Started! Current score is 5
// Hi, I'm a rebel and I don't wait for levelOne

// // delay on async api call for 5 seconds
// Level One reached! New score is 10
Collapse
 
sodic profile image
Filip Sodić • Edited

I realize I'm a bit late to the discussion, but, since this is a fairly popular article and I believe many will be using it as a reference in the future, I chose to write this comment anyway.

Also, keep in mind, I am far from a JS expert, it is entirely possible for me to get something wrong or misinterpret the original article. Then again, if I misinterpreted it, who knows how many others might misinterpret it as well.

With all that said, Alwyn is 100% percent right, the callbacks in the article are not asynchronous and, if you think about it, they really shouldn't be. As stated in the article, a callback is simply a function passed as an argument to another function. It's just like any other argument a function can get. It makes no sense for a callback to be magically asynchronously called just by being there. We would not expect an argument of type Number to make anything async, so why should a function be any different?

Siwalik, all that is called asynchronously in the code you provided as an answer to Alwyn's question is the first argument of the setTimeout function. This function creates an event and attaches the arrow function to it. This arrow function is then called after the event is settled (5 seconds later). The functions startGame, levelOne and callback are all called synchronously. The only thing making the code appear asynchronous is the event you created with setTimeout and this has nothing to do with callbacks.

A good example of proving the synchronous and disproving the asynchronous nature of your original functions is this one:

function levelOne(value, callback) {
    var newScore = value + 5;
    callback(newScore);
    console.log('After callback');
}

function startGame() {
    var currentScore = 5;
    console.log('Game Started! Current score is ' + currentScore);
    levelOne(currentScore, function(levelOneReturnedValue) {
        console.log('Level One reached! New score is ' + levelOneReturnedValue);

        // some useless job to cause waiting
        var a;
        for(var i = 0; i < 1000000000; i++){
            a += i;
        }

        console.log('Done with callback');
    });
    console.log('After levelOne');
}

startGame();

Notice how 'After callback' and 'Done with callback' are printed before 'After levelOne', proving that the callback call is indeed synchronous.

Turns out this 'callbacks being asynchronous' thing is a common misconception. Take a look at this stack overflow thread for more information.

Again, sorry if you knew all of this and I just misunderstood your words.

Thread Thread
 
siwalikm profile image
Siwalik Mukherjee • Edited

Hi @Filip, I appreciate you for taking the time and explaining this in detail.

I realise setTimeout isn't asynchronous but I've naively used it to mock how an async call would actually behave, didn't realise people starting out might get confused thinking setTimeout has to do anything with async.

Update: I went up and replaced the setTimeout I wrote in @Alwin's reply with an actual API call with delay, for correct depiction of javascript's working. :)