← Learning Hub
Intermediate

Asynchronous JavaScript and Promises

Some jobs take time: loading data from the internet, waiting for a timer, reading a file. JavaScript doesn't stop and wait. It starts the job and carries on, then runs your code when the job is done. This is asynchronous code.

Imagine a restaurant where the waiter takes your order and then stands frozen at the kitchen door until your food is ready, ignoring everyone else. That's what a web page would be like if JavaScript waited for slow jobs. Instead, it hands the job off, keeps the page responsive, and handles the result when it's ready.

JavaScript has one main thread, so this asynchronous style is essential. Clicks, scrolling and animations keep working while data loads in the background.

Example
console.log("1. Order placed");
setTimeout(() => console.log("3. Delivered (after 1 second)"), 1000);
console.log("2. Keep shopping");
// Output:
// 1. Order placed
// 2. Keep shopping
// 3. Delivered (after 1 second)

Promises

A Promise is an object for a result that will come later. It is first pending, then either fulfilled (it worked) or rejected (it failed).

A promise is like the token you get at a food counter: it isn't the food, but it's a promise that you'll get the food (or be told it ran out). You attach what to do next with .then() for success and .catch() for failure.

Example
function checkStock(item) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (item === "Pen") resolve("Pen is in stock");
      else reject(new Error(item + " is out of stock"));
    }, 500);
  });
}

checkStock("Pen")
  .then(msg => console.log(msg))           // Output: Pen is in stock
  .catch(err => console.log(err.message))
  .finally(() => console.log("Check done")); // Output: Check done
Example
<!DOCTYPE html>
<html>
  <body>
    <pre id="out"></pre>
    <script>
      function show(...values) {
        document.getElementById("out").textContent += values.join(" ") + "\n";
      }
      function wait(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
      }
      show("Packing your order...");
      wait(1000)
        .then(() => { show("Shipped!"); return wait(1000); })
        .then(() => show("Out for delivery!"))
        .then(() => wait(1000))
        .then(() => show("Delivered ✅"));
    </script>
  </body>
</html>
▶ Try it yourself

Running several at once

Example
const a = Promise.resolve(10);
const b = Promise.resolve(20);
Promise.all([a, b]).then(([x, y]) => console.log(x + y));   // Output: 30
Promise.all waits for all promises and fails if any one fails. Promise.allSettled waits for all and tells you which worked and which failed.
Key points
  • Asynchronous code starts slow jobs and continues without waiting.
  • A Promise is pending, then fulfilled or rejected.
  • .then handles success, .catch handles errors.
  • Promise.all runs several jobs together.

📝 Test yourself

1. In what order does this print? log("A"); setTimeout(() => log("B"), 0); log("C")
2. Which method handles a rejected promise?
3. Fill in the method that waits for many promises together:
Promise.([p1, p2]).then(...)