ai js promise 2026-08-26

write a js promise tutorial

write a js promise tutorial

(ai answer)

Example: Simulating an API call

function fetchUserData(userId) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (userId > 0) {
        resolve({ id: userId, name: "Alice", email: "alice@example.com" });
      } else {
        reject(new Error("Invalid user ID"));
      }
    }, 1000); // simulate network delay
  });
}

3. Consuming a Promise

Using .then() and .catch()

fetchUserData(1)
  .then(user => {
    console.log("User:", user);
  })
  .catch(error => {
    console.error("Error:", error.message);
  })
  .finally(() => {
    console.log("Request finished (success or failure)");
  });

Chaining Promises

Each .then() returns a new Promise, so you can chain them:

fetchUserData(1)
  .then(user => {
    console.log("Got user:", user.name);
    return fetchUserOrders(user.id); // returns another promise
  })
  .then(orders => {
    console.log("Orders:", orders);
    return calculateTotal(orders);
  })
  .then(total => {
    console.log("Total spent:", total);
  })
  .catch(error => {
    console.error("Something failed:", error.message);
  });

4. Promise Static Methods

Promise.resolve() and Promise.reject()

Promise.resolve(42).then(value => console.log(value)); // 42
Promise.reject(new Error("Oops")).catch(err => console.error(err.message));

Promise.all() – Wait for all to succeed

const p1 = Promise.resolve(1);
const p2 = Promise.resolve(2);
const p3 = Promise.resolve(3);

Promise.all([p1, p2, p3])
  .then(results => console.log(results)); // [1, 2, 3]

If any promise rejects, the whole Promise.all rejects immediately.

Promise.allSettled() – Wait for all to settle

Promise.allSettled([
  Promise.resolve("ok"),
  Promise.reject("fail")
]).then(results => {
  console.log(results);
  /*
  [
    { status: "fulfilled", value: "ok" },
    { status: "rejected", reason: "fail" }
  ]
  */
});

Promise.race() – First one to settle wins

Promise.race([
  new Promise(resolve => setTimeout(() => resolve("fast"), 100)),
  new Promise(resolve => setTimeout(() => resolve("slow"), 500))
]).then(result => console.log(result)); // "fast"

Promise.any() – First one to fulfill wins

(Ignores rejections until all have rejected)

Promise.any([
  Promise.reject("fail 1"),
  Promise.resolve("success"),
  Promise.reject("fail 2")
]).then(result => console.log(result)); // "success"

5. Error Handling Best Practices

Always handle rejections. Unhandled promise rejections can cause problems.

// Good
fetchData()
  .then(data => process(data))
  .catch(err => handleError(err));

// Also good – catch at the end of a long chain
doSomething()
  .then(...)
  .then(...)
  .then(...)
  .catch(err => console.error(err));

You can also throw inside a .then to reject the chain:

fetchUserData(1)
  .then(user => {
    if (!user.email) {
      throw new Error("User has no email");
    }
    return user;
  })
  .catch(err => console.error(err.message));

8. Common Patterns & Tips

Parallel vs Sequential

// Sequential (slow)
const a = await fetchA();
const b = await fetchB();

// Parallel (fast)
const [a, b] = await Promise.all([fetchA(), fetchB()]);

Timeout a Promise

function withTimeout(promise, ms) {
  const timeout = new Promise((_, reject) =>
    setTimeout(() => reject(new Error("Timeout")), ms)
  );
  return Promise.race([promise, timeout]);
}

Retry logic

async function retry(fn, retries = 3) {
  try {
    return await fn();
  } catch (err) {
    if (retries <= 0) throw err;
    return retry(fn, retries - 1);
  }
}

9. Quick Reference Cheat Sheet

// Create
const p = new Promise((resolve, reject) => { ... });

// Consume
p.then(value => {}).catch(err => {}).finally(() => {});

// Combinators
Promise.all([...])       // all must succeed
Promise.allSettled([...]) // wait for everything
Promise.race([...])      // first to settle
Promise.any([...])       // first to succeed

// Async/await
async function foo() {
  try {
    const result = await somePromise;
  } catch (e) {
    // handle error
  }
}