Skip to main content

Migrating from Promise chains to Async/Await

Several functions used in Javascript are asynchronous in nature and return Promises and you might need to implement those with traditional Promise syntax using .then() and .catch(). This may seem alright for simpler codes but is bound to become messy with mildly complicated code structures such as loops or chain of conditional statements.
The hard truth is that Promises are now antiquated. A highly-preferred way in such cases is the Async/Await syntax which renders the code much more readable and easier to code.
But I have learnt so much about Promises already!
Don’t worry! The conceptual notion of asynchronous programming you might have learned for using Promises would be a strong base for the learning of Async/Await. It is just different in syntax and the implicit working is quite similar.
Async/Await is just syntactic sugar for promises
We shall discuss the several benefits of Async/Await syntax in brief and we will then also discuss how to migrate from Promise Chains to Async/Await in Javascript.
But first, let’s go through a short introduction to Async/Await.

Async/Await

Async/Await is a way to write asynchronous codes in Javascript. They implicitly use Promises. The primary goal of Async/Await is to make working with Promises easier.
  • As a broad definition, any function that returns a Promise is known as an async function. Therefore, such functions must be preceded by the async keyword.
async function test() {
    // function body
}
const a = async() => {
    // function body
}
// You can use any of the two syntaxes you might prefer to use.
  • The await keyword pauses the execution of the async function and waits for the passed Promise's resolution, and then resumes the async function's execution and returns the resolved value.
  • The await keyword is only valid inside async functions. If you use it outside of an async function’s body, you will get a SyntaxError.
While the async function is paused, the calling function continues running (having received the implicit Promise returned by the async function).

Comparison between the two:-

Implementing an asynchronous function using Promises and maintaining code readability might be a tedious task. Due to the simpler syntax structure of async/await along with its efficient error handling capabilities, async/await seems better than using promises.
Excerpt of code using Promises →
function test(){
 return new Promise((resolve,reject) => {
 resolve('successful');
    });
}

let a = test();
a.then(resolved => console.log(resolved));
Excerpt of code using Async/Await →
async function main() {
 let a = await test();
 console.log(a);
}

function test(){
 return 'successful';
}
As you can see, the syntax for Async/Await is quite straightforward, and chaining is even easier.
Chaining using Promises
function test() {
    return func1()
    .then(v1 => {
        return func2(v1);
    })
    .then(v2 => {
        return func3(v1, v2);
    });
}
Chaining using Async/Await
async function test() {
    let v1 = await func1();
    let v2 = await func2(v1); 
    return await func3(v1, v2);  
}
Easy, isn’t it?

Benefits

Some of the benefits of Async/Await over Promise Chains are:-
  1. Simple syntax, hence, more readable code.
  2. Chaining is very easy.
  3. Only the Promise Chain is asynchronous whereas the entire wrapper function is asynchronous in async/await.
  4. The code becomes quite flexible.
  5. Efficient error handling.
  6. Easier Debugging.
  7. No nested structures of callbacks, therefore, simplified code layout.

How to migrate?

Let us assume we have a piece of code implemented using Promise Chains:-
function restaurantCustomer() {
    return getCustomer()
    .then(customer => {
        return getOrder(customer);
    }).then(order => {
        return prepareFood(order);
    }).then(meal => {
        return serveFood(meal);
    }).then(food => {
        return eatFood(food, customer);
    }).catch(showError);    
}
We now need to migrate to the Async/Await code. Let’s see how we’ll move towards this step-by-step:-
  • Conversion of .then() calls to await
In the traditional promise syntax, the promise resolution was consumed by .then() function and the reject statement was consumed by .catch()function. But in the Async/Await syntax, the function is called by using awaitkeyword which will pause the current function until the called function is resolved.
function restaurantCustomer() {
    let customer = await getCustomer();
    let order = await getOrder(customer);
    let meal = await prepareFood(order);
    let food = await serveFood(meal);
    return await eatFood(food);
}
  • Using async keyword
All functions which use await keyword must strictly be prefixed with the asynckeyword.
async function restaurantCustomer() {
    ...
}
  • Error Handling using try-catch blocks
Error Handling in Promises can be done by appending .catch() function. But error handling in async/await goes old-school and uses the traditional try-catch blocks. This allows us to handle both asynchronous and synchronous errors in one block unlike the case with promises. We will wrap the entire code in a try block followed by a catch block to catch any errors thrown.
async function restaurantCustomer() {
    try{
        ...
    } catch(e) {
        showError(e);
    }
}
The code structure now becomes much more simple and flexible.
Before (Promise Chain)
function restaurantCustomer() {
    return getCustomer()
    .then(customer => {
        return getOrder(customer);
    }).then(order => {
        return prepareFood(order);
    }).then(meal => {
        return serveFood(meal);
    }).then(food => {
        return eatFood(food, customer);
    }).catch(showError);    
}
After (Async/Await)
async function restaurantCustomer() {
    try{
        let customer = await getCustomer();
        let order = await getOrder(customer);
        let meal = await prepareFood(order);
        let food = await serveFood(meal);
        return await eatFood(food);
    } catch(e) {
        showError(e);
    }
}
Note: Some code editors have the facility of converting promises to async/await like VSCode where you can often do this using quick fixes.

Conclusion

While promise chains are built on promises, async/await implicitly use promises and async/await is much more syntax friendly which has a huge effect on your code’s logic and layout.
You can also combine the use of async/await with traditional Promise functions such as promise.all() and promise.race() as per your preference. It is also easy to edit or add features using the async/await syntax which is quite an important thing in any project.

Comments

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...