Created | Urls | Favourites | Opened | Upvotes | Comments |
4 | 0 | 283 | 0 | 0 |
Promises are used mostly for asynchronous operations like eg. XmlHttpRequests :
let promise = new Promise(function(resolve, reject) {
var age;
try {
age = getAge();
resolve(age);
}
catch (ex) {
reject(new Error('could not retrive age : ' + ex));
}
});
The Promise constructor takes a user defined function called the executor as an argument. The Javascript engine feeds the executor two callbacks as arguments by convention called resolve & reject - the executor is invoked immediately upon promise initialization, the executor will do some typically asynchronous work and then finished it must call either resolve or reject.
The callback functions resolve & reject are pre-defined by the Javascript engine, we just call them from within the executor.
A Promise can be in 3 different states :
Then a promise change state from "pending" to either "fulfilled" or "rejected", the promise is said to be settled.
Then the executor settles the promise (that is: calling either the resolve or reject callback), the promise will execute 3 handler methods if you have defined them :
let promise = new Promise((resolve, reject) => {
// Set the status to "fulfilled" after 1 second
// And set the result to "finished"
setTimeout(() => resolve("finished"), 1000);});
promise.then(
result => alert(result); // shows finished after 1 second
error => alert(error); // will not show since the status of the promise is "fulfilled"
}
Both the .then & .catch handlers themselves are returning a promise - this means we can chain promises :
ES5 callbacks
function es5LoadScript(src, callback) {
let script = document.createElement("script");script.src = src;
if (callback) { script.onload = callback; }
script.onerror = (src) => console.log("error loading script : " + src);
document.head.appendChild(script);
}
// usage (the API for topiqs.online contains a 12 level deep callback of this type)
es5LoadScript('urlFirstScript', function() {es5LoadScript('urlSecondScript', function() {
console.log('Finished loading scripts');
});
});
ES6 promises
function es6LoadScript(src) {
return new Promise((resolve, reject) => {
let script = document.createElement("script");
script.src = src;
script.onload = resolve()
script.onerror = reject(new Error("error loading script : " + src);
document.head.appendChild(script);
}
// usage
let promise = es6LoadScript('urlFirstScript');promise.then(
() => es6LoadScript('urlSecondScript')
).then(
() => console.log('Finished loading scripts')
).catch(
(error) => console.log(error.message)
);
So using promises instead of callbacks makes the code more easy to read & maintain because it appears simpler and because it can be written in the natural order that the code executes.