Promise API
Promise API is what async/await language features are built on top of. A Promise is an object that represents an asynchronous result that will either resolve to a value or reject with an error.
Let’s use the setTimeout function to simulate a request that will resolve or reject in future.
// define a function/lambda that returns a Promise
const willThisBeEven = (num, delay_ms) => new Promise(function(resolve, reject) {
const asyncfunc = function() {
if(num < 0) {
reject("No negatives please!"); // failure: reject promise with error
}
if(num % 2 === 0) {
resolve("EVEN!"); // success: resolve promise with a value
} else {
resolve("ODD!");
}
};
setTimeout(asyncfunc, delay_ms);
});
willThisBeEven(5, 3000).then(console.log).catch(console.error); // ODD!
willThisBeEven(6, 6000).then(console.log).catch(console.error); // EVEN!
willThisBeEven(-5, 9000).then(console.log).catch(console.error); // Error: No negatives please!
The basic steps to create a Promise are:
- Instantiate a promise with
new Promise(function callback(resolve, reject) {...}) - The callback receives
resolveandrejectfunctions - The callback performs some asynchronous activity and calls the appropriate function
- Now the promise can be combined with
then/catchorasync/await
(async function() {
try {
console.log(await willThisBeEven(5, 3000));
} catch(e) {
console.error(e);
}
})();