×


Async/await in JavaScript : asynchronous behaviour of Javascript Part -4

For part 1, part 2 and part 3 of this series, see the following links

https://truetocode.com/understanding-callbacks-and-callback-hell-in-javascript-asynchronous-behavior-of-javascript-part-1/697/

https://truetocode.com/understanding-promises-in-javascript-asynchronous-behavior-of-javascript-part-2/730/

https://truetocode.com/generator-functions-in-javascript-asynchronous-behavior-of-javascript-part-3/744/

In the previous three articles in this series, we learned about doing asynchronous operations with callbacks, promises, and generator functions. In ES8 or ES2017 , Javascript introduced a new kind of syntax called async/await, which makes it easier to do asynchronous operations. Async/await syntax is actually just syntactic sugar over promises and callbacks
The following example shows the basic syntax for performing async/await operations. Here too, we use fetch function which returns a promise. Remember that this block of code is run on chrome 60. Earlier versions of Chrome do not support async/ await.

fetch()  and  json() returns promise

Now using async/await

Both will produce output like  the following

The fetch() here returns a promise so we await for fetch. The json() function also returns a promise so we await for that too. Here we can see that using the async/await made the code easier to read and understand.

As you can see that async/await helps you to write code in a way that asynchronous code looks and behave a  more like synchronous code. On each await keyword, the function pauses as you can see in the below example

 

Async/await is just syntactic sugar over promises and Generators. We know that Generator functions can be paused from our previous tutorial. We can extract the value of a promise calling next() which yield the value. The async/await makes use of this and provides us with a better syntax for writing asynchronous code that looks like synchronous code. 

Async await with error catching

 

 

 

Multiple async/await requests at once

 

 

 

Async await with promise.all and map function

 

 

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

 

See the below video from JSConf by Forbes Lindesay

https://www.youtube.com/watch?time_continue=15&v=qbKWsbJ76-s

One Comment

  • callum pearse September 9, 2018 at 2:03 pm

    Goodjob.Thanks a lot

Leave a Reply

Your email address will not be published. Required fields are marked *