JavaScript Promises
What is a Promise?
A Promise is an object representing the eventual completion (or failure) of an asynchronous operation.
A Promise is in one of these states:
- pending: initial state, neither fulfilled nor rejected.
- fulfilled: meaning that the operation completed successfully.
- rejected: meaning that the operation failed.
Creating a Promise
A Promise is created using the new Promise() constructor, which
takes a function (executor) with two arguments: resolve and
reject.
Chaining Promises
The then() method returns a new Promise, allowing you to
chain multiple asynchronous operations.
Promise.all()
The Promise.all() method takes an iterable of promises
as an input, and returns a single Promise that resolves to an array
of the results of the input promises.
Summary
- Promises provide a cleaner way to handle asynchronous operations than callbacks.
- Use
resolve()for success andreject()for failure. - Use
then()to handle success andcatch()to handle errors. Promise.all()waits for multiple promises to complete.
Quick Quiz
Which method is used to handle a rejected Promise?
Enjoying these tutorials?