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.
thenreturns a new promise that resolves with the callback's return value.- If a
thencallback returns a promise, the chain waits for it. - A throw or rejection skips ahead to the next
catch. finallyruns in both cases and passes the result through.
Read more
- Promise basics (https://javascript.info/promise-basics)javascript.info
- Promises chaining (https://javascript.info/promise-chaining)javascript.info