Promise For The Newby, How Promises Works in Javascript
What is a Promise?
A Promise is an object that represents the eventual completion or failure of an asynchronous operation and its resulting value. A Promise is used to handle asynchronous operations and provide a way to avoid callback hell.
A Promise can be in one of three states:
- Pending: The initial state. The promise is neither fulfilled nor rejected.
- Fulfilled: The operation completed successfully, and the promise has a resulting value.
- Rejected: The operation failed, and the promise has a reason for the failure.
Creating a Promise
To create a Promise in JavaScript, you use the Promise constructor. The constructor takes a single argument: a function called the “executor” function. The executor function takes two parameters: “resolve” and “reject”. These are functions that you call to change the Promise’s state.
Here’s an example of creating a Promise that resolves with a value after a delay:
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Hello, world!');
}, 1000);
});
In this example, the Promise will resolve with the string “Hello, world!” after a delay…