Luke Oliff.

TIL: Chaining Promises With Async Await in Node.js

·TIL·1 min read·Luke Oliff

Before async await, Node.js code looked like a stair case of nested callbacks or a chain of .then() calls. Async await flattens it.

async function getCallDetails(callId) {
  const response = await fetch(`https://api.example.com/v1/calls/${callId}`)
  const data = await response.json()
  return data
}

The async keyword marks the function. await pauses until the Promise resolves. Errors go into a try/catch the same as synchronous code.

async function main() {
  try {
    const call = await getCallDetails('ABC123')
    console.log(call.status)
  } catch (err) {
    console.error('Failed:', err.message)
  }
}

Node.js supported async await natively since version 8. If you were still writing callbacks in 2019, this one change made your code easier to read and easier to reason about.

Can I use await outside an async function?

Not in Node.js 8 through 12. Top-level await arrived in Node 14. Wrap everything in an async main() function.

Does async await replace Promises entirely?

No. async await is syntactic sugar over Promises. You still need Promise.all() for concurrent operations.