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

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...