A Promise in JavaScript is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. It allows you to handle asynchronous operations more easily compared to callbacks, making the code cleaner and easier to manage.
.catch()
instead of handling them at each callback level..then()
, making the code easier to follow.A Promise can have three states:
Here's an example of a Promise:
fetchData()
is called:
success = true
, the promise moves to the fulfilled state, and resolve()
returns the result.success = false
, the promise moves to the rejected state, and reject()
returns the error message..then()
handles the successful response..catch()
handles the error case.This example demonstrates how Promises simplify asynchronous operations and make error handling more manageable.