JavaScript Promises
"I Guarantee a Outcome!"
"Creating code" refers to code that may require a certain amount of time.
"Consuming code" refers to code that needs to pause and wait for a result.
A promise is like a connection between the code that creates something and the code that uses it.
JavaScript Promise Object
A promise includes the code that generates a result and the code that uses that result.
Promise Syntax
let myPromise = new Promise(function(myResolve, myReject) {
myResolve();
myReject();
});
myPromise.then(
function(value) { /* code if successful */ },
function(error) { /* code if some error */ }
);
When the code creating something gets the outcome, it needs to trigger one of the two callbacks:
When | Call |
Success | myResolve(result value) |
Error | myReject(error object) |
Promise Object Properties
A JavaScript Promise object can have these qualities:
- Pending
- Fulfilled
- Rejected
The Promise object has two properties: state and result.
When a Promise object is still in progress, the outcome is not yet defined.
When a Promise is successfully completed, it produces a specific value.
When a Promise is marked as "rejected," it means there is an error.
myPromise.state | myPromise.result |
"pending" | undefined |
"fulfilled" | a result value |
"rejected" | an error object |
You're not allowed to view the Promise attributes state and result.
You need to utilize a Promise method for managing promises.
Promise How To
Here's how you can use a Promise:
myPromise.then(
function(value) { /* code if successful */ },
function(error) { /* code if some error */ }
);
Promise.then() requires two inputs: one for handling success and another for managing failure.
You don't have to use both, just choose whether you want to add a callback for success or failure.
JavaScript Promise Examples
To show how promises work, we'll use the callback examples discussed in the previous chapter:
- Anticipating a Delay
- File is not ready yet.
Waiting for a Timeout
Waiting for a file
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Promise Object</h1>
<h2>The then() Method</h2>
<p id="demo"></p>
<script>
function myDisplayer(some) {
document.getElementById("demo").innerHTML = some;
}
let myPromise = new Promise(function(myResolve, myReject) {
let x = 0;
// some code (try to change x to 5)
if (x == 0) {
myResolve("OK");
} else {
myReject("Error");
}
});
myPromise.then(function(value) {
myDisplayer(value);
}, function(error) {
myDisplayer(error);
});
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<h2>setInterval() with a Callback</h2>
<p>Wait 3 seconds (3000 milliseconds) for this page to change.</p>
<h1 id="demo"></h1>
<script>
setTimeout(function() {
myFunction("I love Coding !!!");
}, 3000);
function myFunction(value) {
document.getElementById("demo").innerHTML = value;
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Promise Object</h1>
<h2>The then() Metod</h2>
<p>Wait 3 seconds (3000 milliseconds) for this page to change.</p>
<h1 id="demo"></h1>
<script>
const myPromise = new Promise(function(myResolve, myReject) {
setTimeout(function() {
myResolve("I love Coding !!");
}, 3000);
});
myPromise.then(function(value) {
document.getElementById("demo").innerHTML = value;
});
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Callbacks</h2>
<p id="demo"></p>
<script>
function myDisplayer(some) {
let img = document.createElement('img');
img.src = some;
document.getElementById("demo").appendChild(img);
}
function getFile(myCallback) {
let req = new XMLHttpRequest();
req.onload = function() {
if (req.status == 200) {
let blob = new Blob([this.response], { type: 'image/png' });
let url = URL.createObjectURL(blob);
myCallback(url);
} else {
myCallback("Error: " + req.status);
}
}
req.open('GET', "https://propertutorials.com/assets/files/car.png");
req.responseType = 'blob';
req.send();
}
getFile(myDisplayer);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Promise Object</h1>
<h2>The then() Metod</h2>
<p id="demo"></p>
<script>
function myDisplayer(some) {
document.getElementById("demo").innerHTML = some;
}
let myPromise = new Promise(function(myResolve, myReject) {
let req = new XMLHttpRequest();
req.open('GET', "mycar.html");
req.onload = function() {
if (req.status == 200) {
myResolve(req.response);
} else {
myReject("File not Found");
}
};
req.send();
});
myPromise.then(function(value) {
myDisplayer(value);
}, function(error) {
myDisplayer(error);
});
</script>
</body>
</html>