JavaScript Promises
A Promise represents the eventual result of an asynchronous operation.
It acts as a placeholder for a value that is not available yet.
Instead of waiting for the operation to finish, JavaScript continues running other code.
When the operation completes, the Promise is either fulfilled with a value or rejected with an error.
Why Promises?
Callbacks work well for simple asynchronous tasks.
However, when several asynchronous operations depend on each other, callbacks can become deeply nested.
Promises provide a cleaner and more readable way to organize asynchronous code.
Example
step1(function(result1) {
step2(result1, function(result2) {
step3(result2, function(result3) {
display(result3);
});
});
});
The style above is often called callback hell.
Promises let you write the same logic in a cleaner way.
Same Flow with Promises
Example
step1()
.then(step2)
.then(step3)
.then(display);
Each then() waits for the previous Promise to finish.
The code is flatter and easier to read.
Promise States
A Promise acts as a placeholder for a value that will be available at some point in the future, allowing you to handle asynchronous code in a cleaner way than traditional callbacks.
Every Promise is always in one of 3 states.
State Description
Pending The initial state.
The operation has started but is not fulfilled or rejected.
Fulfilled The operation has completed and a value is available.
Rejected The operation has failed and a value (error) is available.
Pending
│
├────────► Fulfilled
│
└────────► Rejected
A promise is considered settled if it is fulfilled or rejected (not pending).
Promises and JavaScript APIs
Many web APIs return promises.
fetch() is a common example.
Example
fetch("fetch.txt")
.then(function(response) {
return response.text();
})
.then(function(data) {
myDisplayer(data);
})
.catch(function(error) {
myDisplayer(error);
});
This is promise-based async programming.
Most of the time you will use Promises returned by JavaScript APIs.
But you can also create your own Promise.
Creating a Promise
Here is how to CREATE a Promise:
Syntax
let myPromise = new Promise(function(resolve, reject) {
// Code that may take some time
resolve(value); // when successful
reject(value); // when error
});
The promise constructor takes a function with two parameters.
Parameter Description
resolve function to run if finishes successfully
reject function to run if finishes with an error
Call resolve() when the operation succeeds.
Call reject() when it fails.
Using a Promise
Here is how to USE a Promise:
Syntax
// USE a Promise
myPromise.then(
function(value) { /* code if success */ },
function(value) { /* code if error */ }
);
then() takes two arguments, one callback function for success and another for failure.
Both are optional, so you can add a callback function for success or failure only.
Examples
// Create a Promise
let myPromise = new Promise(function(resolve, reject) {
// Code that may take some time
let success = true;
if (success) {
resolve("Done");
} else {
reject("Failed");
}
});
// Use the Promise
myPromise.then(
function(value) {myDisplayer(value);},
function(value) {myDisplayer(value);}
);
// Create a Promise
let myPromise = new Promise(function(resolve, reject) {
// Code that may take some time
let success = false;
if (success) {
resolve("Done");
} else {
reject("Failed");
}
});
// Use the Promise
myPromise.then(
function(value) {myDisplayer(value);},
function(value) {myDisplayer(value);}
);
A promise represents a value that will be available later.
A promise is a container for a future result.
The result can be a value or an error.
The then() Method
The then() method runs when a Promise is fulfilled.
Example
fetch("fetch.txt")
.then(function(response) {
return response.text();
})
.then(function(data) {
myDisplayer(data);
});
The first then() receives the fetch response.
The second then() receives the data returned by the first.
The catch() Method
If a Promise is rejected, catch() handles the error.
Example
fetch("fetch.txt")
.then(function(response) {
return response.text();
})
.then(function(data) {
myDisplayer(data);
})
.catch(function(error) {
myDisplayer(error);
});
Top comments (0)