Async and Await in JavaScript/TypeScript

0
2543
views

Sometimes in your code you want to execute functions serially that is one line after another as JavaScript is in asynchronous nature whenever it encounters callbacks or API calls it won’t wait for the result to arrive. It simply jumps to the next line of execution. API calls and callback functions will be pushed into the callback queue once they finish executing it will pick up the result.

Till Node version 7.6, the callbacks were the only way to achieve to run functions one after another. As Node architecture is single-threaded and asynchronous.

To achieve serialization with callback functions is very messy and after the time when your code increases it results in callback hell.

CallBack Example:

app.get('/', function(){
 function1(arg1, function(){
   ...
})
});

After sometime node was rolled out with promises and function chaining

Promises Example

function fun1(req, res){
  return request.get('http://localhost:3000')
   .catch((err) =>{
     console.log('found error');
}).then((res) =>{
   console.log('get request returned.');
});

When node v8 was released it came up with new feature async and await It completely avoids function chaining with then and catch methods.

Using async and await keywords you can now clearly tell functions. This is asynchronous function and we need to await for this result. This feature is pretty easy to use.

Async and Await Example:

async function fun1(req, res){
  let response = await request.get('http://localhost:3000');
    if (response.err) { console.log('error');}
    else { console.log('fetched response');
}