Full Stack LAMP - MEAN Developer, Python developer. Certified Azure Developer. Freelance programmer/consultant/trainer.

How to use top-level await in Node.js

Top-level await enables developers to use the await keyword outside of async functions. Starting from Node.js v14 top-level await is available and it is only available in ES modules. This means you can not use it with common js modules.

Async/await

Async/await is the syntactical modification of promises to avoid chaining. It makes the code a lot cleaner and easier to understand. The await keyword makes the code halt until the promise is resolved or rejected.

(async function() {
  let getData = await axios('https://arjunphp.com/api')
  console.log(getData.data)
}());

The new behavior

await axios('https://arjunphp.com/api');

Leave a Reply