How to implement Top-level await in Node.js

For junior to mid-level developers, there is a common coding method of always using the await keyword strictly inside an asynchronous JavaScript function. However Top-level await is a technique that allows us to use the await keywords inside asynchronous functions without throwing annoying errors.

Therefore some steps are to be taken to avoid instances like this and I would be sharing some with you in this article.

Why is it important?

The use of Top-level await is very essential in some use cases like;

Resource Initialization

const connection = await dbConnector();

Dynamic Dependency pathing

const strings = await import(/i18n/${navigator.language});

Prerequisites

To follow through with this tutorial, you need;

  • Good knowledge of JavaScript

  • Node.js installed

  • Vscode

  • Axios package

Brief Background of JavaScript Promises

Promises is a basic JavaScript technique used to handle asynchronous operations. A promise can either be fulfilled, pending or rejected. When an API call is made to a server, its default state would be pending. It then turns into fulfilled if the data is successfully and if an error occurs, then it would be in the rejected state.

The await keyword is known to act like a barricade to JavaScript, forcing it to wait until a promise is resolved and it returns a result

How To Implement it

First, you need to initiate a Node project and install the Axios package. Then you can copy the following code below

We would be using a free API that helps us fetch dummy data of users randomly.

As expected, we have a response after we made a fetch request to that API. Now to switch and implement the top-level await, we would make an edit to our package.json file to make sure we have node version 14 or greater (you can use the node -v command to check your current node version).

"type": "module", "engines" :{ "node" : "^14" },

After editing, you can return to the index.js file and make the following changes

Conclusion

We have seen what to integrate on how to use top-level await in Nodejs. This technique would help in preventing all sorts of bugs that come when applying this. Feel free to share if you were successfully able to follow through

Credit

Tom does tech