Archives

Categories

Meta

Async Await

Previously we had a small introduction on Promises which are used in asynchronous events and getting data after an event occurs, Async Await is a JavaScript API that allows you to write asynchronous code in a synchronous manner so that your code is easier to read and debug.

Async Await is just different syntax for using Promises, they use promises in the background. Most browsers support Async Await, you can get the full list here.

Promises are some event that takes a little bit of time to resolve and pass data to you. An simple example is getting data from an remote API, when you make the request to the API, you have to wait for the request to go from your device to the server, the server then processes your request and then sends back the result.

Promise ‘then’ method is called then the promise is completed and you can handle the data if you like, similarly Async Await allows you to wait till the event finishes so that you can continue.

Methods

Async Await has only 2 methods

Async

If you want to use Async Await, you have to declare the function as an async function.

Normal function

function getImage(url){………}

Async function

async function getImage(url){………}

Await

Await make the execution of the program pause at the statement until the promise is resolved.

var image = await getImage(url);

In the above line, the image variable will get the data only after the getImage promise is resolved.

Example

Lets now look at an example to see the syntactic differences between Promises and Async Await.

In the above code snippet , we perform the same code using Async Await, the gotMyMoney function is the same, we create a new async function checkStatus as Await will only work inside async functions, next we write the code as if the code is syncronous, this is the main advantage of Async Await.

Error Handling

If the promise that contains the data fails or rejects, then the await statement will throw an error, you can handle it in two ways

try catch

Simply surround the await statement in a try catch block and handle the promise rejection in the catch block