JavaScript Promise Object
The Promise Object represents the completion or failure of an asynchronous operation and its results.
A Promise can have 3 states:
| pending | initial state |
| rejected | operation failed |
| fulfilled | operation completed |
Example
// Create a Promise Object
let myPromise = new Promise(function(myResolve, myReject) {
let result = true;
// Code that may take some time goes here
if (result == true) {
myResolve("OK");
} else {
myReject("Error");
}
});
// Using then() to display result
myPromise.then(x => myDisplay(x), x => myDisplay(x));
JavaScript Promise Methods and Properties
| Name | Description |
|---|---|
| Promise.all() | Returns a single Promise from a list of promises When all promises fulfill |
| Promise.allSettled() | Returns a single Promise from a list of promises When all promises sette |
| Promise.any() | Returns a single Promise from a list of promises When any promise fulfills |
| Promise.race() | Returns a single Promise from a list of promises When the faster promise settles |
| Promise.reject() | Returns a Promise object rejected with a value |
| Promise.resolve() | Returns a Promise object resolved with a value |
| catch() | Provides a function to be called when a promise is rejected |
| finally() | Provides a function to be called when a promise is fulfilled or rejected |
| then() | Provide two functions to be called when a promise is fulfilled or rejected |