A Promise is a JavaScript object that links "Producing Code" and "Consuming Code". Producing code is code that can take some time. Consuming code is code that must wait for the result.
A JavaScript Promise object can be in one of three states:
let myPromise = new Promise(function(myResolve, myReject) {
// "Producing Code" (May take time)
if (success) {
myResolve("OK"); // Success!
} else {
myReject("Error"); // Failure!
}
});
// "Consuming Code" (Must wait for a settled Promise)
myPromise.then(
function(value) { /* success */ },
function(error) { /* error */ }
);
For better readability, most developers use .then() for success and
.catch() for errors.
myPromise
.then(value => console.log(value))
.catch(error => console.log(error));
let dataFetch = new Promise((resolve, reject) => {
let success = true;
setTimeout(() => {
if (success) resolve("Data Loaded!");
else reject("Server Error");
}, 2000);
});
dataFetch.then(res => console.log(res));
resolve() to finish successfully and return datareject() to return an error reason.then() and
.catch()