Posted by admin at January 14, 2020
The promise constructor takes one argument, a callback with two parameters, resolve and reject. Do something within the callback, perhaps async, then call resolve if everything worked, otherwise call reject.
A promise is an object which can be returned synchronously from an asynchronous function. It will be in one of 3 possible states:
onFulfilled()
will be called (e.g., resolve()
was called)onRejected()
will be called (e.g., reject()
was called)A promise is settled if it’s not pending (it has been resolved or rejected). Sometimes people use resolved and settled to mean the same thing: not pending.
Once settled, a promise can not be resettled. Calling resolve()
or reject()
again will have no effect. The immutability of a settled promise is an important feature.
This is a real-life analogy for things we often have in programming:
const promise1 = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('foo');
}, 300);
});
promise1.then(function(value) {
console.log(value);
// expected output: "foo"
});
console.log(promise1);
// expected output: [object Promise]
Comments