A JavaScript Promise object can be in one of three states:
The Promise object has two key properties: state and result.
While the Promise is pending (in progress), the result is undefined.
When the Promise is fulfilled, the result contains a value.
When the Promise is rejected, the result contains an error object.
myPromise.state |
myPromise.result |
“pending” |
undefined |
“fulfilled” |
a result value |
“rejected” |
an error object |
You cannot directly access the state and result properties of a Promise. Instead, you need to use Promise methods like .then(), .catch(), or .finally() to handle the outcome of a Promise. |
This is how you can use a Promise:
myPromise.then( function(value) { /* code if successful */ }, function(error) { /* code if some error */ } ); |
function myDisplayer(some) { document.getElementById(“demo”).innerHTML = some; } let myPromise = new Promise(function(myResolve, myReject) { let x = 0; // The producing code (this may take some time) if (x == 0) { myResolve(“OK”); } else { myReject(“Error”); } }); myPromise.then( function(value) {myDisplayer(value);}, function(error) {myDisplayer(error);} ); |