The evolving history of asynchronous operation in JavaScript

  sonic0002        2019-11-09 08:21:56       6,069        0    

JavaScript is single threaded, it means there would be only one task running at any point of time. But this would slow down the overall program execution if there is long running task, hence asynchronous task execution is desired in complex cases. To achieve asynchronous task execution, there are a few options introduced in JavaScript.

  • setTimeout/setInterval
  • Event
  • Promise
  • Async/Await

setTimeout/setInterval is one of the first mechanisms introduced in JavaScript to simulate asynchronous operations. Since these operations are not executing in sequence, there would be a potential issue on how data/state gets synced. Assuming there is a long running task needing a bit time to run and the normal process shouldn't be blocked but some operations later depend on the output of setTimeout/setInterval function.

In this case, a callback maybe needed so that it can be invoked when the function in setTimeout/setInterval completes. But this approach has a problem where the code becomes unreadable if there are too many callbacks in a nested call chain.

// callback
function callback(name){
    console.log("callback name: " + name);
}

setTimeout(function(cb){
    let name = "test";
    cb(name);
}(callback), 0);

Hence there comes the Promise in ECMAScript 2015, from its name, it ensures that the function either in then() or catch() would be invoked when resolution or rejection happens and the codes in executor would execute asynchronously along with the main thread code. This approach makes the code more intuitive to understand.

// promise
function callback(name){
    console.log("callback name: " + name);
}

let promise = new Promise(function(resolve, reject){
    // Execute some asynchonours code
    // Maybe fefect an online image

    setTimeout(function(){
        resolve("promise");
    }, 1000);
});
promise.then(function(name){
    callback(name);
}).catch(function(error){
    console.error(error);
});

In ECMAScript 2017 specification, there is even a further update to the Promise mechanism to improve code readability. It introduces two new keywords: async and await. These two will enable you to write asynchronous code just like normal sequential code. async and await indeed are promise based.

// async/await
function callback(name){
    console.log("callback name: " + name);
}

var promise = new Promise(function(resolve, reject){
    // Execute some asynchonours code
    // Maybe fefect an online image
    
    setTimeout(function(){
        resolve("promise");
    }, 1000);
});

async function run(){
    try {
       name = await promise;
    } catch (ex) {
        console.log("error");
    }
    callback(name);
}

run();

The code with async and await looks just like sequential executed code but they are actually running asynchronously. This greatly improves the code readability and makes it easier to maintain.

Apart from all these, there is also event based asynchronous code execution where the code will only be executed when a specified event is fired like button click event. 

AWAIT  JAVASCRIPT  ASYNC  PROMISE 

       

  RELATED


  0 COMMENT


No comment for this article.



  RANDOM FUN

Is this sarcasm?