CodePark/ questions / Promises & async/await
START PRACTICINGPRACTICE
Frontend question · JavaScript › Promises & async/await

What is a Promise? Explain its states and how chaining works.

A Promise is an object that stands for the future result of an async operation. Think of a restaurant buzzer: you get it now, and it tells you later if your food is ready or if something went wrong.

A promise has three states:

  • pending: the work is not finished yet. Every promise starts here.
  • fulfilled: the work succeeded, with a value.
  • rejected: the work failed, with a reason.

A promise settles (becomes fulfilled or rejected) only once. After that it never changes.

How chaining works:

  • then(onFulfilled, onRejected) registers callbacks. It always returns a new promise.
  • The new promise resolves with whatever the callback returns.
  • If the callback returns a promise, the chain waits for that promise.
  • If the callback throws, the new promise rejects.

This is what makes flat chains possible, instead of callbacks nested inside callbacks.

A rejection skips then handlers until it reaches a catch, or a then with a second argument. catch can recover by returning a value, and then the chain continues. finally runs on both success and failure, and passes the original result through.

Promise callbacks always run asynchronously, as microtasks.

  • A promise starts pending, then becomes fulfilled or rejected, and settles only once.
  • then returns a new promise that resolves with the callback's return value.
  • If a then callback returns a promise, the chain waits for it.
  • A throw or rejection skips ahead to the next catch.
  • finally runs in both cases and passes the result through.