A Promise represents a value that may be available now, later, or never.
const promise = new Promise((resolve, reject) => {
const success = true;
if (success) resolve("Done");
else reject(new Error("Failed"));
});
.then/.catchpromise
.then(result => console.log(result))
.catch(error => console.error(error.message));
async and awaitasync functions always return a Promise. await pauses inside async functions until a Promise settles:
async function run() {
try {
const result = await promise;
console.log(result);
} catch (err) {
console.error(err.message);
}
}
delay(ms, value) that returns a Promise resolving with value after ms milliseconds.loadMessage() that:
delay(10, "Hello Async")safeDivide(a, b) that:
Error("Division by zero") when b === 0a / bloadMessage() and safeDivide(10, 2), then display in #output: "HELLO ASYNC | 10/2 = 5".A Promise has 3 states: pending, fulfilled, rejected.