Async Await in JavaScript / Typescript 

Async-Await are new keywords that are introduced in ES2017 to write async functions. Basically, what it means is that you can write promises in a more readable way. Let’s take a look at this with an example.

Consider the following code for a promise.

The above function will return a promise and that promise will be resolved in 2000 milliseconds.

We will call the function as follows.

Here when the promise is resolved after 2000 milliseconds then success function will be called and the successDatavariable will get whatever was passed with the resolve. This is a standard promise code there is nothing special about it.

 

Converting Promises Into Async-Await

Now, let’s go ahead and convert the promise to Async-Await. The promiseFun() will remain the same as the Aysnc functions are meant to handle how the promises are handled. So the above code can be converted as follows.

Note here that we have to declare the function as async with the async keyword. Then on line 2, we have the awaitkeyword before calling the promiseFun(). Keep in mind that when a function is declares using the async keyword the function must have await in its body.

As promises are asynchronous, the console.log message will only be executed after the promise has finished. So in our case, the console message will show up after 2000milliseconds.

If the pomise fails or returns an error then nothing after the line containing the Await keyword will execute.

Handling Errors / Reject In Async-Await

In the above code, we converted our promise to use Async-Await, but we only handled the part when the promise is resolved. In other words, the above function will not handle promise reject. To handle that we will need to add a try-catch block as follows.

As shown, when the promise is rejected then the catch() block will execute with whatever was passed in the promise reject.

 

Handling Multiple Promises with Async-Await

Up to now we saw how you can handle promises with Async-Await. But, we were only handling one promise. What if you want to chain promises together using Async-Await. We as easily do that the following way.

As shown, we are calling two functions which return promise. As we are using the Async-Await keywords Line 4 will only be executed if link 3 is successful. Also, note that using Async-Await we can handle the Error/Reject at on place in the catch() block.

 

Conclusion

Personally, I love Async-Await as it has a clearer syntax and have been using it in my projects. Before you start using it in your projects make sure that the browser you which to target supports it. You can check for browser support of Async-Await using caniuse.com.

 

 

En poursuivant votre navigation sur mon site, vous acceptez l’utilisation des Cookies et autres traceurs  pour réaliser des statistiques de visites et enregistrer sur votre machine vos activités pédagogiques. En savoir plus.