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.

keyword pauses the execution of the async function and waits for the passed 's resolution, and then resumes the 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:-

Simple syntax, hence, more readable code. Chaining is very easy. Only the Promise Chain is asynchronous whereas the entire wrapper function is asynchronous in async/await. The code becomes quite flexible. Efficient error handling. Easier Debugging. No nested structures of callbacks, therefore, simplified code layout.

But what if you already have legacy code using Promises? How to migrate now?

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 await keyword 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 async keyword.

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.

A recent AfterAcademy open-source project adopted the async execution for Promises. Check out the project: NodeJS Backend Architecture using Typescript

Let me know your feedback in the comments below.

Happy Learning!