JavaScript Promise.then() method is called when a promise is resolved.
Syntax
promise.then(onFulfilled[, onRejected]);
promise.then(value => {
// fulfillment
}, reason => {
// rejection
});
Parameters
It takes two callback function parameters:
- onFulfilled(required): A function to be executed if the promise is resolved successfully.
- onRejected(optional): A function to be executed if the promise is rejected.
Return Value
It returns that Promise is fulfilled or rejected, and the corresponding handler function (onFulfilled or onRejected) will be called asynchronously (scheduled in the current thread loop).
Visual Representation
Example 1: Using Promise.then() method
let promise = new Promise((resolve, reject) => {
// Fulfill the promise with value after 500 ms
setTimeout(() => {
resolve("Data received successfully");
}, 500);
});
promise.then(
result => console.log(result), // onFulfilled function
);
Output
Data received successfully
Example 2: Rejecting the promise
let promise = Promise.reject(new Error('Something went wrong!'));
promise.then(null, err => {
console.log(err.message);
});
Output
Something went wrong!
Example 3: Promise chaining
In promise chaining, the value returned from a .then() method is used as the resolution for the next promise in the chain.
Due to this chaining mechanism, you don’t need to catch errors in each individual .then() If you put .catch() at the end of your promise chain, any errors in the promise chain will bypass the rest of the promise chain and go straight to your .catch() error handler.
let promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(2);
}, 200);
});
promise
.then(result => {
console.log(result);
return result * 2;
})
.then(result => {
console.log(result);
return result * 3;
})
.then(result => {
console.log(result);
});
Output
2
4
12
Browser Compatibility
- Chrome 32 and above
- Edge 12 and above
- Firefox 29 and above
- Opera 19 and above
- Safari 8 and above
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.