Skip to content

Conversation

@blazejkustra
Copy link

@blazejkustra blazejkustra commented Sep 18, 2025

TL;DR rules:

  1. Use await when steps need to run sequentially.
  2. Use await … catch when you want simple, localized error handling.
  3. Use Promise.all(...) when steps can run in parallel.
  4. Use async functions when writing a function that runs sequential logic without callbacks.
  5. Use Promises directly when you’re wrapping a callback and need to call resolve/reject yourself.
  6. Use a deferred Promise for signals like “ready to load” or “wait until condition”.

Examples:

Sequential with await:

async function runSequentially() {
  await login();
  await seedDb();
  const result = await runJob();
  return verify(result);
}

Simple localized error handling:

async function getData(url: string) {
  const data = await fetch(url).catch(() => fetchFallback(url));
  return process(data);
}

Parallel with Promise.all:

const [user, permissions] = await Promise.all([
  getUser(),
  getPermissions(),
]);

Wrapping a callback with a Promise:

function readFileAsync(path: string): Promise<string> {
  return new Promise((resolve, reject) => {
    fs.readFile(path, "utf8", (err, data) => {
      if (err) reject(err);
      else resolve(data);
    });
  });
}

Deferred promise for signaling readiness:

let resolveReady: () => void;

const isReady = new Promise<void>((resolve) => {
  resolveReady = resolve;
});

// later in the code
resolveReady();

@blazejkustra blazejkustra changed the title add example for async await usage Example async/await usage Sep 18, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants