Native Promises
suggest changeA promise represents one future result. It starts pending. It settles once, either fulfilled or rejected, and does not go back to pending. That fits an action that completes a single time, not a stream of events. Create one with new Promise(function (resolve, reject) {}).
The function passed into the Promise constructor always receives a first and second parameter usually named resolve and reject respectively. The naming of these two parameters is convention, but they will put the promise into either the ‘resolved’ state or the ‘rejected’ state. When either one of these is called the promise goes from being ‘pending’ to ‘settled’. resolve is called when the desired action, which is often asynchronous, has been performed and reject is used if the action has errored.
In the example below, timeout returns a promise.
function timeout (ms) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve("It was resolved!");
}, ms)
});
}
timeout(1000).then(function (dataFromPromise) {
// logs "It was resolved!"
console.log(dataFromPromise);
})
console.log("waiting...");
console output
waiting...
// << pauses for one second>>
It was resolved!
When timeout is called the function passed to the Promise constructor is executed without delay. Then the setTimeout method is executed and its callback is set to fire in the next ms milliseconds, in this case ms=1000. Since the callback to the setTimeout isn’t fired yet the timeout function returns control to the calling scope. The chain of then methods are then stored to be called later when/if the Promise has resolved. If there were catch methods here they would be stored as well, but would be fired when/if the promise ‘rejects’.
The script then prints ‘waiting…’. One second later the setTimeout calls its callback which calls the resolve function with the string “It was resolved!”. That string is then passed into the then method’s callback and is then logged to the user.
In the same sense you can wrap the asynchronous setTimeout function which requires a callback you can wrap any singular asynchronous action with a promise.
The language reference is Using promises on MDN.