async / await

Write asynchronous code that reads top to bottom.

Syntaxasync function f() { await promise; }

async/await is modern syntax over promises. Mark a function async, then await a promise to pause until it resolves — no callbacks, no chaining.

Comparing callbacks, promises, and async await stylesCallbackfn(function (err,data) {if (err) ...use(data)})Promisefn().then(use).catch(fail)async / awaittry {const d =await fn()} catch (e) {}
The same task in three styles — async/await reads the most naturally.

Example

Example · javascript
const fs = require('fs/promises');

async function loadConfig() {
  try {
    const text = await fs.readFile('config.json', 'utf8');
    const config = JSON.parse(text);
    console.log('Loaded port:', config.port);
  } catch (err) {
    console.error('Could not load config:', err.message);
  }
}
loadConfig();

When to use it

  • An API route handler is declared `async` so it can `await` a database query and send the result in the same linear flow without `.then()` chains.
  • A migration script uses `async/await` inside a `for` loop to apply database changes one at a time and abort on the first failure.
  • An integration test uses `async` functions so each test step reads like synchronous code, making assertion failures easy to trace.

More examples

Async function with await

Declares an `async` function that awaits a promise and returns its result -- reads like synchronous code.

Example · js
const { readFile } = require('fs/promises');

async function loadJson(file) {
  const raw = await readFile(file, 'utf8');
  return JSON.parse(raw);
}

loadJson('config.json').then(cfg => console.log(cfg.port));

Try/catch error handling

Wraps `await` calls in a `try/catch` block to handle both network errors and JSON parse failures.

Example · js
async function fetchData(url) {
  try {
    const res  = await fetch(url);
    const data = await res.json();
    return data;
  } catch (err) {
    console.error('Fetch failed:', err.message);
    throw err; // re-throw so the caller can handle it
  }
}

Sequential vs parallel with await

Contrasts sequential `await` (waits for each in turn) with `Promise.all` (both I/O calls start simultaneously).

Example · js
const { readFile } = require('fs/promises');

async function main() {
  // Sequential (one at a time):
  const a = await readFile('a.txt', 'utf8');
  const b = await readFile('b.txt', 'utf8');

  // Parallel (both start at once):
  const [c, dd] = await Promise.all([
    readFile('c.txt', 'utf8'),
    readFile('d.txt', 'utf8'),
  ]);
}
main();

Discussion

  • Be the first to comment on this lesson.