What a promise is in JavaScript
A pending value that settles once, and never changes after.
const promise = new Promise((resolve, reject) => {
console.log("executor runs now");
setTimeout(() => resolve("settled"), 10);
setTimeout(() => resolve("ignored"), 20);
});
console.log("after the constructor");
promise.then((value) => console.log("then:", value));
Promise.resolve("already done").then((value) => console.log(value));
Promise.reject(new Error("nope")).catch((error) => console.log(error.message));
How it works
- The executor runs immediately, synchronously.
resolveorrejectsettles it; later calls do nothing.thenalways runs asynchronously, after the current task.
Keywords and builtins used here
Promisecatchconst
The run, in numbers
- Lines
- 12
- Characters to type
- 416
- Tokens
- 122
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 77 seconds.
Step 2 of 5 in Promises, step 2 of 19 in Promises & async.