Understanding Async Await in JavaScript | ES6

By : FiveMinute  |  Updated On : 15 hours ago

Understanding Async Await in JavaScript | ES6

To learn async await you must have to be knowledge of Promises in javascript. Async await is alternate of Promises and it is developed to write cleaner code and easy understandable. If you write async keyword in any function then that function will behave asynchronous. Await keyword is only permitted inside the function if the function is declared with the Async keyword. Await keyword is used to handle only promises and it wait till the promise resolved than it execute the next line of the code. But when it waits for the promise to resolve it doesn't block the thread it goes out of the function and keep execution continously. Also we can use multiple await inside the async function.

Syntax for async await.

async function name([param[, param[, ...param]]]) {
   const data = await api.get('https://example.com/api/data.json');
   console.log(data);
}
//here api.get return promise

 

To learn async await first I show you a simple example of promises and convert the same example with async await. Also learn how to handle the error in async await.

Create a function which make request and return promise.

function makeRequest(location) {
    return new Promise((resolve, reject) => {
        console.log(`Making Request to ${location}`);
        if (location === 'Google') {
            resolve('Google says hi');
        } else {
            reject('We can only talk to Google');
        }
    })
}

Now handle the response from another function which return promise.

function processRequest(response) {
    return new Promise((resolve, reject) => {
        console.log('Processing response');
        resolve(`Extra Information + ${response}`);
    })
}

Next call the makeRequest function with Google parameter.

makeRequest('Google').then(response => {
    console.log('Response Received');
    return processRequest(response);
}).then(processedResponse => {
    console.log(processedResponse);
})

//output
Making request to google
Response received
Processing response
Extra information + Google says hi

In the above code you can there is no catch block for error handling as Google is the correct parameter. Now implement catch block with wrong parameter Facebook.

makeRequest('Facebook').then(response => {
    console.log('Response Received');
    return processRequest(response);
}).then(processedResponse => {
    console.log(processedResponse);
}).catch(err => {
    console.log(err);
});

//output
Making request to Facebook
We can only talk to Google

Now use above Promise code with async await example.

async function doWork(location) {
    const response = await makeRequest(location);
    console.log('Response Received');
    const processedResponse = await processRequest(response);
    console.log(processedResponse);
}
doWork('Google');

//output
Making request to google
Response received
Processing response
Extra information + Google says hi

You can see the same console with async await also with lesser and easy understandable code.

Now use same async await code with wrong parameter and let's look what happened.

doWork('Facebook');

output :

Making request to google
Uncaught (in promise) We can only talk to Google

As you can see above code thrown error and it is not handled by the async await code. Best way to handle the error in async await is write async code on try catch block like below.

async function doWork(location) {

    try {
        const response = await makeRequest(location);
        console.log('Response Received');
        const processedResponse = await processRequest(response);
        console.log(processedResponse);
    } catch (err) {
        console.log(err);
    }
}
doWork('Facebook');

//Output
//Making request to Facebook
//We can only talk to Google

In above code promise error is handled by the catch block.

That's all to understand the async await with the conversion of Promise code to async await.