What are Promises?
A Promise represents the eventual result of an asynchronous operation. It either succeeds with a resolved value or fails with a rejection reason. Promises provide a cleaner and more manageable way to handle asynchronous code compared to callbacks.
Think of a promise as a container holding a value that might not be available yet, but will be resolved when the operation completes.
Promise States
A promise has three possible states:
- pending: The promise is in progress, waiting for the operation to complete.
- fulfilled: The promise has successfully completed, and the resolved value is available.
- rejected: The promise failed, and a rejection reason is available.
Creating Promises
There are several ways to create promises:
Promise.resolve(10) // Immediately resolved promise
Promise.reject(new Error('Something went wrong')) // Immediately rejected promise
Promise.resolve(setTimeout(() => { console.log('Hello from Promise!'); }, 1000))
// You can also use the 'new' keyword, but it's less common now:
// const myPromise = new Promise((resolve, reject) => { ... });
Common Promise Methods
- resolve(value): Settles the promise with the given value.
- reject(reason): Settles the promise with the given reason.
- finally(): Executes regardless of whether the promise was resolved or rejected.