https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.
Essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function.
let promise = doSomething();
promise.then(successCallback, failureCallback);
or simply:
doSomething().then(successCallback, failureCallback);
We call this an asynchronous function call. This convention has several advantages. We will explore each one.
Guarantees
Unlike old-style passed-in callbacks, a promise comes with some guarantees:
- Callbacks will never be called before the completion of the current run of the JavaScript event loop.
- Callbacks added with
.then
even after the success or failure of the asynchronous operation, will be called, as above. - Multiple callbacks may be added by calling
.then
several times, to be executed independently in insertion order.
But the most immediate benefit of promises is chaining.
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
}
function get() {
return getRandomInt(0, 61) % 2 === 0 ? true : false;
}
let promiseIsEven = new Promise(function(resolve, reject) {
if(get()) {
resolve('success ' + new Date().getMilliseconds());
} else {
reject('failure ' + new Date().getMilliseconds());
}
});
promiseIsEven.then(function(fromResolve) {
console.log(fromResolve);
}).catch(function(fromReject) {
console.log(fromReject);
});