"Producing code" is code that can take some time.
"Consuming code" is code that can must wait for the result.
A Promise is an Object that links Producing code and Consuming code.
Promise
let myPromise = new Promise(function(resolve, reject) {
// Producing Code (May take some time)
setTimeout(() => resolve([1, 2, 3]), 3000);
});
// Consuming Code (Must wait for a fulfilled Promise)
myPromise.then(
function(value) { console.log(value); },
function(error) { console.log(error); }
);
async and await make promises easier to write.
"async" makes a function return a Promise.
"await" makes a function wait for a Promise.
async/await
// The keyword 'async' before a function makes the function return a Promise.
let myFunction = async function() {
return [1, 2, 3];
}
myFunction().then(
function(value) { console.log(value); }
);
1. Recursive call using a Promise
let myFunction = function() {
return new Promise(function(resolve) {
setTimeout(() => resolve([1, 2, 3]), 3000);
}).then(function(value) {
console.log(value);
myFunction();
});
}
myFunction();
2. Recursive call using async/await
let myFunction = async function() {
let myPromise = new Promise(function(resolve) {
setTimeout(() => resolve([1, 2, 3]), 3000);
});
// The 'await' keyword can only be used inside an 'async' function.
// The 'await' keyword makes the function pause the execution and wait for a resolved Promise before it continues.
console.log(await myPromise);
myFunction();
}
myFunction();