Thuta Learning
Node.js
IntermediateWeb Developmentbeginner

Asynchronous Node.js with Promises and async/await

What you'll walk away with

  • Await a Promise
  • Tell sequential and concurrent work apart
  • Handle async errors

Let's break it down simply

Node.js uses asynchronous APIs so the event loop doesn't get blocked while waiting on I/O operations. An async function returns a Promise, and await just pauses that function until the Promise settles. You can run independent requests at the same time with Promise.all.

javascript
import { readFile } from 'node:fs/promises'

async function loadConfig() {
  try {
    const [app, messages] = await Promise.all([
      readFile('./app.json', 'utf8'),
      readFile('./messages.json', 'utf8')
    ])
    return { app: JSON.parse(app), messages: JSON.parse(messages) }
  } catch (error) {
    throw new Error('Could not load configuration', { cause: error })
  }
}

const config = await loadConfig()
console.log(config.app.name)
You should see
Tutorial API

Try It Yourself

Read two JSON files both sequentially and with Promise.all, then compare the execution time.

Discover Promises in Node.js — Node.js

Easy traps

  • Using a Promise's value directly without await
  • Awaiting independent tasks sequentially for no reason
  • Not handling a rejected promise

Exercise

Read two JSON files both sequentially and with Promise.all, then compare the execution time.

You'll know it worked when: Tutorial API

Asynchronous Node.js with Promises and async/await | Thuta Learning