withResolvers and timers in JavaScript
The newer helpers: a promise you settle from outside, and awaitable sleep.
function deferred() {
const { promise, resolve, reject } = Promise.withResolvers();
return { promise, resolve, reject };
}
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function main() {
const gate = deferred();
setTimeout(() => gate.resolve("opened"), 5);
console.log(await gate.promise);
const started = Date.now();
await sleep(10);
console.log("slept:", Date.now() - started >= 9);
const failing = deferred();
failing.reject(new Error("closed"));
console.log(await failing.promise.catch((e) => e.message));
}
main();
How it works
Promise.withResolvershands back the promise and its two functions.- That replaces the let-declared resolve trick.
setTimeoutwrapped in a promise is the sleep JavaScript lacks.
Keywords and builtins used here
DatePromiseasyncawaitcatchconstfunctionreturn
The run, in numbers
- Lines
- 22
- Characters to type
- 557
- Tokens
- 166
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 95 seconds.
Step 2 of 3 in Scheduling, step 13 of 19 in Promises & async.