Promises in JavaScript
Constructing a promise and chaining its outcomes.
function delay(ms, value) {
return new Promise((resolve, reject) => {
if (ms < 0) reject(new Error("negative delay"));
setTimeout(() => resolve(value), ms);
});
}
delay(100, "done")
.then((result) => result.toUpperCase())
.catch((error) => `failed: ${error.message}`)
.finally(() => console.log("settled"));
How it works
- The executor receives
resolveandreject. thentransforms the value;catchhandles errors.finallyruns either way.
Keywords and builtins used here
Promisecatchfinallyfunctionifreturn
The run, in numbers
- Lines
- 11
- Characters to type
- 308
- Tokens
- 100
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 63 seconds.
Step 1 of 5 in Promises, step 1 of 19 in Promises & async.