JavaScript Promises
A JavaScript Promise object contains both the producing code and calls to the consuming code. It is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
Promise Syntax
javascript
let myPromise = new Promise(function(myResolve, myReject) {
// "Producing Code" (May take some time)
let x = 0;
if (x == 0) {
myResolve("OK");
} else {
myReject("Error");
}
});
myPromise.then(
function(value) { /* code if successful */ console.log(value); },
function(error) { /* code if some error */ console.log(error); }
);Async/Await
async and await make promises easier to write. async makes a function return a Promise. await makes a function wait for a Promise.
javascript
async function myFunction() {
let myPromise = new Promise(/*...*/);
let result = await myPromise;
console.log(result);
}
myFunction();Test Yourself with an Exercise
Which keyword is used to make a function wait for a Promise?