Reading history

JavaScript Promises and async/await Explained

5 min read 1 views

Learn asynchronous JavaScript: the event loop, promises, then, catch and finally, async functions with await, and Promise.all for parallel tasks.

Some work takes time: downloading data, reading a file, waiting for a timer. JavaScript does not freeze while it waits. It starts the slow task, carries on with other code, and deals with the result when it arrives. This is called asynchronous code. Promises represent those future results, and the async/await keywords let you write asynchronous code that reads almost like normal step-by-step code.

In this lesson you will learn

  • Why asynchronous code runs “out of order”
  • What a promise is and its three states
  • Using .then(), .catch() and .finally()
  • Writing async functions with await
  • Running tasks in parallel with Promise.all

Callbacks, Timers and Promises

console.log("1. Start");

setTimeout(() => {
  console.log("3. Timer finished (after 0 ms!)");
}, 0);

console.log("2. End of main code");

// A promise wraps a result that arrives later
function wait(ms, value) {
  return new Promise((resolve) => setTimeout(() => resolve(value), ms));
}

function checkStock(item) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (item === "pen") resolve(`${item}: 12 in stock`);
      else reject(new Error(`${item}: not found`));
    }, 50);
  });
}

wait(100, "4. Waited 100 ms")
  .then((msg) => {
    console.log(msg);
    return checkStock("pen");
  })
  .then((msg) => console.log("5.", msg))
  .then(() => checkStock("laptop"))
  .catch((err) => console.log("6. Error:", err.message))
  .finally(() => console.log("7. Done"));

Output

1. Start
2. End of main code
3. Timer finished (after 0 ms!)
4. Waited 100 ms
5. pen: 12 in stock
6. Error: laptop: not found
7. Done
  • Even with a 0 ms delay, the setTimeout callback runs after the rest of the main code. JavaScript finishes the current code first, then picks up waiting tasks from its event loop.
  • A promise is an object for a value that is not ready yet. It starts pending, then becomes either fulfilled with a value (by calling resolve) or rejected with an error (by calling reject).
  • .then() runs when the promise is fulfilled. Returning another promise from .then() chains the steps in order.
  • .catch() handles a rejection anywhere earlier in the chain; .finally() runs either way.

async and await

const wait = (ms, value) =>
  new Promise((resolve) => setTimeout(() => resolve(value), ms));

async function getUser(id) {
  await wait(100);
  if (id <= 0) throw new Error("Invalid id");
  return { id, name: id === 1 ? "Arif" : "Mitu" };
}

async function getOrders(userId) {
  await wait(100);
  return userId === 1 ? ["Book", "Pen"] : ["Bag"];
}

async function main() {
  // One after another
  const user = await getUser(1);
  const orders = await getOrders(user.id);
  console.log(user.name, "ordered", orders.join(", "));

  // In parallel: both start at once
  const t0 = Date.now();
  const [a, b] = await Promise.all([getUser(1), getUser(2)]);
  const ms = Date.now() - t0;
  console.log("Parallel:", a.name, b.name, ms < 180 ? "(about 100 ms, not 200)" : "");

  // Errors work with try/catch
  try {
    await getUser(-1);
  } catch (err) {
    console.log("Caught:", err.message);
  }
}

main();

Output

Arif ordered Book, Pen
Parallel: Arif Mitu (about 100 ms, not 200)
Caught: Invalid id
  • An async function always returns a promise. Inside it, await pauses that function until a promise settles and then gives you its value. The rest of the program keeps running meanwhile.
  • Code with await reads top to bottom: get the user, then get their orders. The equivalent .then() chain would be harder to follow.
  • Awaiting one task after another runs them in sequence. When tasks do not depend on each other, start them together with Promise.all([...]); here both lookups finish in about 100 ms instead of 200 ms.
  • A rejected promise behaves like a thrown error, so ordinary try…catch works with await.

Promise Helpers

HelperResolves when
Promise.all([...])All succeed (rejects as soon as one fails)
Promise.allSettled([...])All finish, reporting each success or failure
Promise.race([...])The first one settles, either way
Promise.any([...])The first one succeeds

Common Mistakes

  1. Forgetting await, so you get a pending Promise object instead of the data.
  2. Using await outside an async function in an ordinary script, which is a syntax error. (Modules allow top-level await.)
  3. Awaiting independent tasks one by one when Promise.all would be faster.
  4. No catch, leaving “Uncaught (in promise)” errors in the console.

Practice Exercises

Exercise 1. Write delay(ms) that returns a promise, then use it to print “Go!” after one second.

Show answer
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function start() {
  await delay(1000);
  console.log("Go!");
}
start();

Exercise 2. Print a countdown 3, 2, 1 with one second between numbers.

Show answer
async function countdown() {
  for (let i = 3; i >= 1; i--) {
    console.log(i);
    await delay(1000);
  }
  console.log("Lift off!");
}
countdown();

Frequently Asked Questions

Is JavaScript multi-threaded?

Your JavaScript code runs on a single thread. The browser or Node.js handles timers and network requests in the background and queues your callbacks to run when they are ready. Web Workers can add extra threads for heavy work.

Should I use .then() or async/await?

They do the same thing. async/await is usually easier to read, especially with several steps and error handling, so most modern code prefers it.

Summary

  • Asynchronous tasks finish later; JavaScript keeps running meanwhile.
  • A promise is pending, then fulfilled or rejected.
  • async/await writes promise code step by step; use try/catch for errors.
  • Promise.all runs independent tasks in parallel.

Next: The Fetch API.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *