node/test/parallel/test-timers-promises-scheduler.js
James M Snell 8bce46aff1
timers: add experimental scheduler api
Adds experimental implementations of the yield and wait APIs being
explored at https://github.com/WICG/scheduling-apis.

When I asked the WHATWG folks about the possibility of standardizing the
[awaitable versions of setTimeout/setImmediate](https://github.com/whatwg/html/issues/7340)
that we have implemented in `timers/promises`, they pointed at the work
in progress scheduling APIs draft as they direction they'll be going.
While there is definitely a few thing in that draft that have
questionable utility to Node.js, the yield and wait APIs map cleanly to
the setImmediate and setTimeout we already have.

Signed-off-by: James M Snell <jasnell@gmail.com>

PR-URL: https://github.com/nodejs/node/pull/40909
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com>
Reviewed-By: Darshan Sen <raisinten@gmail.com>
2021-12-05 07:36:50 -08:00

51 lines
1.1 KiB
JavaScript

'use strict';
const common = require('../common');
const { scheduler } = require('timers/promises');
const { setTimeout } = require('timers');
const {
strictEqual,
rejects,
} = require('assert');
async function testYield() {
await scheduler.yield();
process.emit('foo');
}
testYield().then(common.mustCall());
queueMicrotask(common.mustCall(() => {
process.addListener('foo', common.mustCall());
}));
async function testWait() {
let value = 0;
setTimeout(() => value++, 10);
await scheduler.wait(15);
strictEqual(value, 1);
}
testWait().then(common.mustCall());
async function testCancelableWait1() {
const ac = new AbortController();
const wait = scheduler.wait(1e6, { signal: ac.signal });
ac.abort();
await rejects(wait, {
code: 'ABORT_ERR',
message: 'The operation was aborted',
});
}
testCancelableWait1().then(common.mustCall());
async function testCancelableWait2() {
const wait = scheduler.wait(10000, { signal: AbortSignal.abort() });
await rejects(wait, {
code: 'ABORT_ERR',
message: 'The operation was aborted',
});
}
testCancelableWait2().then(common.mustCall());