Promises to the Rescue
Explore JavaScript promises to understand their three states: pending, resolved, and rejected. Learn how promises simplify asynchronous programming by enabling chaining and clear separation of data and error handling. Gain skills to write cleaner code that effectively manages asynchronous operations using then() and catch() methods.
Newer asynchronous functions in JavaScript are designed to return a promise instead of taking a callback.
Definition: A promise is an object through which a function may propagate an error or result sometime in the future.
States
At any time, a promise is in one of three states:
- Pending
- Resolved
- Rejected
Pending
If an asynchronous function has not completed its task, the promise it returned will be in the pending state.
Resolved
Whenever the asynchronous function completes successfully, it will set the promise into the resolved state. At this time, the promise generates or emits the result passed through it; we refer to this as the promise resolves.
Rejected
If an asynchronous function finishes with an error, it sets the promise into the rejected state. At this time, the promise generates or emits the error passed through it; we refer to this as the promise rejects.
📍A promise may be created in ...