- Courses
- 💻Programming Languages
- 🌐JavaScript
- Core Objects
- Promises
On this page
Promises in JavaScript
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
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 associate handlers with an asynchronous action’s eventual success value or failure reason.
We will discuss Promises more in detail in our module on Asynchronous JavaScript. This lesson will serve as an introduction on Promises as one of the core JavaScript objects.
Creating a Promise
You can create a Promise using the new Promise() syntax. The Promise constructor takes one argument, a callback with two parameters, resolve and reject. Do something within the callback, perhaps async, then call resolve if everything worked, otherwise call reject.
let myPromise = new Promise(function (myResolve, myReject) {
// "Producing Code" (May take some time)
myResolve(); // when successful
myReject(); // when error
});
Consuming a Promise
The then() method is used to schedule code to be run if the Promise is fulfilled or rejected. The then() method returns a Promise. It takes up to two arguments: callback functions for the success and failure cases of the Promise.
myPromise.then(
function (value) {
/* code if successful */
},
function (error) {
/* code if some error */
},
);
Promise States
A Promise is in one of these states:
pending: initial state, neither fulfilled nor rejected.fulfilled: meaning that the operation was completed successfully.rejected: meaning that the operation failed.
The eventual state of a pending promise can either be fulfilled with a value or rejected with a reason (error). When either of these options occur, the associated handlers queued up by a promise’s then method are called.
Chaining Promises
The then() method returns a Promise, which allows for method chaining. If the function passed as handler to then returns a Promise, an equivalent Promise will be exposed to the subsequent then in the method chain.
let promise = new Promise(function (resolve, reject) {
setTimeout(() => resolve(1), 1000);
});
promise
.then(function (result) {
console.log(result); // 1
return result * 2;
})
.then(function (result) {
console.log(result); // 2
return result * 2;
})
.then(function (result) {
console.log(result); // 4
return result * 2;
});
Error Handling
The catch() method returns a Promise and deals with rejected cases only. It behaves the same as calling Promise.prototype.then(undefined, onRejected). In fact, catch(onRejected) is internally implemented as then(undefined, onRejected).
myPromise.catch(function (reason) {
console.log("Handle rejected Promise (" + reason + ") here.");
});
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Sets
Next
MinHeap implementation
- Creating a Promise
- Consuming a Promise
- Promise States
- Chaining Promises
- Error Handling
