1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-12-22 07:14:47 -05:00

chore(cli): Migrate some unit tests to "Promise.withResolvers()" (#21128)

Migrate to use `Promise.withResolvers()` instead of `deferred` in some
of the tests in `cli/tests/unit/`.
Issue: #21041
This commit is contained in:
Tareque Md Hanif 2023-11-11 03:29:09 +06:00 committed by GitHub
parent df14835b83
commit eff3e43296
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
11 changed files with 123 additions and 114 deletions

View file

@ -1,6 +1,5 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
import { assertEquals } from "../../../test_util/std/testing/asserts.ts"; import { assertEquals } from "../../../test_util/std/testing/asserts.ts";
import { deferred } from "../../../test_util/std/async/deferred.ts";
Deno.test("BroadcastChannel worker", async () => { Deno.test("BroadcastChannel worker", async () => {
const intercom = new BroadcastChannel("intercom"); const intercom = new BroadcastChannel("intercom");
@ -12,7 +11,7 @@ Deno.test("BroadcastChannel worker", async () => {
const worker = new Worker(url, { type: "module", name: "worker" }); const worker = new Worker(url, { type: "module", name: "worker" });
worker.onmessage = () => intercom.postMessage(++count); worker.onmessage = () => intercom.postMessage(++count);
const promise = deferred(); const { promise, resolve } = Promise.withResolvers<void>();
intercom.onmessage = function (e) { intercom.onmessage = function (e) {
assertEquals(count, e.data); assertEquals(count, e.data);
@ -21,7 +20,7 @@ Deno.test("BroadcastChannel worker", async () => {
} else { } else {
worker.terminate(); worker.terminate();
intercom.close(); intercom.close();
promise.resolve(); resolve();
} }
}; };

View file

@ -1,5 +1,5 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
import { assertEquals, assertThrows, deferred } from "./test_util.ts"; import { assertEquals, assertThrows } from "./test_util.ts";
const sleep = (time: number) => new Promise((r) => setTimeout(r, time)); const sleep = (time: number) => new Promise((r) => setTimeout(r, time));
@ -151,12 +151,12 @@ Deno.test(async function basicTest() {
Deno.env.set("DENO_CRON_TEST_SCHEDULE_OFFSET", "100"); Deno.env.set("DENO_CRON_TEST_SCHEDULE_OFFSET", "100");
let count = 0; let count = 0;
const promise = deferred(); const { promise, resolve } = Promise.withResolvers<void>();
const ac = new AbortController(); const ac = new AbortController();
const c = Deno.cron("abc", "*/20 * * * *", () => { const c = Deno.cron("abc", "*/20 * * * *", () => {
count++; count++;
if (count > 5) { if (count > 5) {
promise.resolve(); resolve();
} }
}, { signal: ac.signal }); }, { signal: ac.signal });
try { try {
@ -172,19 +172,23 @@ Deno.test(async function multipleCrons() {
let count0 = 0; let count0 = 0;
let count1 = 0; let count1 = 0;
const promise0 = deferred(); const { promise: promise0, resolve: resolve0 } = Promise.withResolvers<
const promise1 = deferred(); void
>();
const { promise: promise1, resolve: resolve1 } = Promise.withResolvers<
void
>();
const ac = new AbortController(); const ac = new AbortController();
const c0 = Deno.cron("abc", "*/20 * * * *", () => { const c0 = Deno.cron("abc", "*/20 * * * *", () => {
count0++; count0++;
if (count0 > 5) { if (count0 > 5) {
promise0.resolve(); resolve0();
} }
}, { signal: ac.signal }); }, { signal: ac.signal });
const c1 = Deno.cron("xyz", "*/20 * * * *", () => { const c1 = Deno.cron("xyz", "*/20 * * * *", () => {
count1++; count1++;
if (count1 > 5) { if (count1 > 5) {
promise1.resolve(); resolve1();
} }
}, { signal: ac.signal }); }, { signal: ac.signal });
try { try {
@ -201,11 +205,15 @@ Deno.test(async function overlappingExecutions() {
Deno.env.set("DENO_CRON_TEST_SCHEDULE_OFFSET", "100"); Deno.env.set("DENO_CRON_TEST_SCHEDULE_OFFSET", "100");
let count = 0; let count = 0;
const promise0 = deferred(); const { promise: promise0, resolve: resolve0 } = Promise.withResolvers<
const promise1 = deferred(); void
>();
const { promise: promise1, resolve: resolve1 } = Promise.withResolvers<
void
>();
const ac = new AbortController(); const ac = new AbortController();
const c = Deno.cron("abc", "*/20 * * * *", async () => { const c = Deno.cron("abc", "*/20 * * * *", async () => {
promise0.resolve(); resolve0();
count++; count++;
await promise1; await promise1;
}, { signal: ac.signal }); }, { signal: ac.signal });
@ -213,7 +221,7 @@ Deno.test(async function overlappingExecutions() {
await promise0; await promise0;
} finally { } finally {
await sleep(2000); await sleep(2000);
promise1.resolve(); resolve1();
ac.abort(); ac.abort();
await c; await c;
} }

View file

@ -3,7 +3,6 @@ import {
assert, assert,
assertEquals, assertEquals,
assertRejects, assertRejects,
deferred,
delay, delay,
fail, fail,
unimplemented, unimplemented,
@ -1260,13 +1259,13 @@ Deno.test(
Deno.test( Deno.test(
{ permissions: { net: true } }, { permissions: { net: true } },
async function fetchNoServerReadableStreamBody() { async function fetchNoServerReadableStreamBody() {
const done = deferred(); const { promise, resolve } = Promise.withResolvers<void>();
const body = new ReadableStream({ const body = new ReadableStream({
start(controller) { start(controller) {
controller.enqueue(new Uint8Array([1])); controller.enqueue(new Uint8Array([1]));
setTimeout(() => { setTimeout(() => {
controller.enqueue(new Uint8Array([2])); controller.enqueue(new Uint8Array([2]));
done.resolve(); resolve();
}, 1000); }, 1000);
}, },
}); });
@ -1274,7 +1273,7 @@ Deno.test(
await assertRejects(async () => { await assertRejects(async () => {
await fetch(nonExistentHostname, { body, method: "POST" }); await fetch(nonExistentHostname, { body, method: "POST" });
}, TypeError); }, TypeError);
await done; await promise;
}, },
); );

View file

@ -1,21 +1,16 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
import { import { assert, assertEquals, assertNotEquals } from "./test_util.ts";
assert,
assertEquals,
assertNotEquals,
deferred,
} from "./test_util.ts";
Deno.test({ Deno.test({
sanitizeOps: false, sanitizeOps: false,
sanitizeResources: false, sanitizeResources: false,
}, async function queueTestNoDbClose() { }, async function queueTestNoDbClose() {
const db: Deno.Kv = await Deno.openKv(":memory:"); const db: Deno.Kv = await Deno.openKv(":memory:");
const promise = deferred(); const { promise, resolve } = Promise.withResolvers<void>();
let dequeuedMessage: unknown = null; let dequeuedMessage: unknown = null;
db.listenQueue((msg) => { db.listenQueue((msg) => {
dequeuedMessage = msg; dequeuedMessage = msg;
promise.resolve(); resolve();
}); });
const res = await db.enqueue("test"); const res = await db.enqueue("test");
assert(res.ok); assert(res.ok);

View file

@ -5,7 +5,6 @@ import {
assert, assert,
assertEquals, assertEquals,
} from "../../../test_util/std/testing/asserts.ts"; } from "../../../test_util/std/testing/asserts.ts";
import { deferred } from "../../../test_util/std/async/deferred.ts";
Deno.test("messagechannel", async () => { Deno.test("messagechannel", async () => {
const mc = new MessageChannel(); const mc = new MessageChannel();
@ -13,14 +12,14 @@ Deno.test("messagechannel", async () => {
assert(mc.port1); assert(mc.port1);
assert(mc.port2); assert(mc.port2);
const promise = deferred(); const { promise, resolve } = Promise.withResolvers<void>();
mc.port2.onmessage = (e) => { mc.port2.onmessage = (e) => {
assertEquals(e.data, "hello"); assertEquals(e.data, "hello");
assertEquals(e.ports.length, 1); assertEquals(e.ports.length, 1);
assert(e.ports[0] instanceof MessagePort); assert(e.ports[0] instanceof MessagePort);
e.ports[0].close(); e.ports[0].close();
promise.resolve(); resolve();
}; };
mc.port1.postMessage("hello", [mc2.port1]); mc.port1.postMessage("hello", [mc2.port1]);
@ -38,7 +37,7 @@ Deno.test("messagechannel clone port", async () => {
assert(mc.port1); assert(mc.port1);
assert(mc.port2); assert(mc.port2);
const promise = deferred(); const { promise, resolve } = Promise.withResolvers<void>();
mc.port2.onmessage = (e) => { mc.port2.onmessage = (e) => {
const { port } = e.data; const { port } = e.data;
@ -46,7 +45,7 @@ Deno.test("messagechannel clone port", async () => {
assert(e.ports[0] instanceof MessagePort); assert(e.ports[0] instanceof MessagePort);
assertEquals(e.ports[0], port); assertEquals(e.ports[0], port);
e.ports[0].close(); e.ports[0].close();
promise.resolve(); resolve();
}; };
mc.port1.postMessage({ port: mc2.port1 }, [mc2.port1]); mc.port1.postMessage({ port: mc2.port1 }, [mc2.port1]);

View file

@ -5,7 +5,6 @@ import {
assertNotEquals, assertNotEquals,
assertRejects, assertRejects,
assertThrows, assertThrows,
deferred,
delay, delay,
execCode, execCode,
execCode2, execCode2,
@ -795,10 +794,10 @@ Deno.test(
async function netCloseWriteSuccess() { async function netCloseWriteSuccess() {
const addr = { hostname: "127.0.0.1", port: listenPort }; const addr = { hostname: "127.0.0.1", port: listenPort };
const listener = Deno.listen(addr); const listener = Deno.listen(addr);
const closeDeferred = deferred(); const { promise: closePromise, resolve } = Promise.withResolvers<void>();
listener.accept().then(async (conn) => { listener.accept().then(async (conn) => {
await conn.write(new Uint8Array([1, 2, 3])); await conn.write(new Uint8Array([1, 2, 3]));
await closeDeferred; await closePromise;
conn.close(); conn.close();
}); });
const conn = await Deno.connect(addr); const conn = await Deno.connect(addr);
@ -815,7 +814,7 @@ Deno.test(
await assertRejects(async () => { await assertRejects(async () => {
await conn.write(new Uint8Array([1, 2, 3])); await conn.write(new Uint8Array([1, 2, 3]));
}); });
closeDeferred.resolve(); resolve();
listener.close(); listener.close();
conn.close(); conn.close();
}, },

View file

@ -5,19 +5,18 @@ import {
assertNotStrictEquals, assertNotStrictEquals,
assertStringIncludes, assertStringIncludes,
assertThrows, assertThrows,
deferred,
} from "./test_util.ts"; } from "./test_util.ts";
Deno.test({ permissions: { hrtime: false } }, async function performanceNow() { Deno.test({ permissions: { hrtime: false } }, async function performanceNow() {
const resolvable = deferred(); const { promise, resolve } = Promise.withResolvers<void>();
const start = performance.now(); const start = performance.now();
let totalTime = 0; let totalTime = 0;
setTimeout(() => { setTimeout(() => {
const end = performance.now(); const end = performance.now();
totalTime = end - start; totalTime = end - start;
resolvable.resolve(); resolve();
}, 10); }, 10);
await resolvable; await promise;
assert(totalTime >= 10); assert(totalTime >= 10);
}); });

View file

@ -1,5 +1,5 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
import { assertEquals, assertThrows, deferred, delay } from "./test_util.ts"; import { assertEquals, assertThrows, delay } from "./test_util.ts";
Deno.test( Deno.test(
{ ignore: Deno.build.os !== "windows" }, { ignore: Deno.build.os !== "windows" },
@ -110,7 +110,7 @@ Deno.test(
permissions: { run: true }, permissions: { run: true },
}, },
async function signalListenerTest() { async function signalListenerTest() {
const resolvable = deferred(); const { promise, resolve } = Promise.withResolvers<void>();
let c = 0; let c = 0;
const listener = () => { const listener = () => {
c += 1; c += 1;
@ -124,10 +124,10 @@ Deno.test(
} }
await delay(20); await delay(20);
Deno.removeSignalListener("SIGUSR1", listener); Deno.removeSignalListener("SIGUSR1", listener);
resolvable.resolve(); resolve();
}); });
await resolvable; await promise;
assertEquals(c, 3); assertEquals(c, 3);
}, },
); );
@ -138,7 +138,7 @@ Deno.test(
permissions: { run: true }, permissions: { run: true },
}, },
async function multipleSignalListenerTest() { async function multipleSignalListenerTest() {
const resolvable = deferred(); const { promise, resolve } = Promise.withResolvers<void>();
let c = ""; let c = "";
const listener0 = () => { const listener0 = () => {
c += "0"; c += "0";
@ -169,10 +169,10 @@ Deno.test(
} }
await delay(20); await delay(20);
Deno.removeSignalListener("SIGUSR2", listener0); Deno.removeSignalListener("SIGUSR2", listener0);
resolvable.resolve(); resolve();
}); });
await resolvable; await promise;
// The first 3 events are handled by both handlers // The first 3 events are handled by both handlers
// The last 3 events are handled only by handler0 // The last 3 events are handled only by handler0
assertEquals(c, "010101000"); assertEquals(c, "010101000");

View file

@ -1,5 +1,5 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
import { assertEquals, Deferred, deferred, fail } from "./test_util.ts"; import { assertEquals, fail } from "./test_util.ts";
const { const {
core, core,
@ -11,8 +11,10 @@ const LOREM =
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."; "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
// Hello world, with optional close // Hello world, with optional close
// deno-lint-ignore no-explicit-any function helloWorldStream(
function helloWorldStream(close?: boolean, completion?: Deferred<any>) { close?: boolean,
cancelResolve?: (value: unknown) => void,
) {
return new ReadableStream({ return new ReadableStream({
start(controller) { start(controller) {
controller.enqueue("hello, world"); controller.enqueue("hello, world");
@ -21,7 +23,9 @@ function helloWorldStream(close?: boolean, completion?: Deferred<any>) {
} }
}, },
cancel(reason) { cancel(reason) {
completion?.resolve(reason); if (cancelResolve != undefined) {
cancelResolve(reason);
}
}, },
}).pipeThrough(new TextEncoderStream()); }).pipeThrough(new TextEncoderStream());
} }
@ -61,8 +65,7 @@ function longStream() {
} }
// Long stream with Lorem Ipsum text. // Long stream with Lorem Ipsum text.
// deno-lint-ignore no-explicit-any function longAsyncStream(cancelResolve?: (value: unknown) => void) {
function longAsyncStream(completion?: Deferred<any>) {
let currentTimeout: number | undefined = undefined; let currentTimeout: number | undefined = undefined;
return new ReadableStream({ return new ReadableStream({
async start(controller) { async start(controller) {
@ -74,7 +77,9 @@ function longAsyncStream(completion?: Deferred<any>) {
controller.close(); controller.close();
}, },
cancel(reason) { cancel(reason) {
completion?.resolve(reason); if (cancelResolve != undefined) {
cancelResolve(reason);
}
if (currentTimeout !== undefined) { if (currentTimeout !== undefined) {
clearTimeout(currentTimeout); clearTimeout(currentTimeout);
} }
@ -185,40 +190,44 @@ Deno.test(async function readableStream() {
// Close the stream after reading everything // Close the stream after reading everything
Deno.test(async function readableStreamClose() { Deno.test(async function readableStreamClose() {
const cancel = deferred(); const { promise: cancelPromise, resolve: cancelResolve } = Promise
const rid = resourceForReadableStream(helloWorldStream(false, cancel)); .withResolvers();
const rid = resourceForReadableStream(helloWorldStream(false, cancelResolve));
const buffer = new Uint8Array(1024); const buffer = new Uint8Array(1024);
const nread = await core.ops.op_read(rid, buffer); const nread = await core.ops.op_read(rid, buffer);
assertEquals(nread, 12); assertEquals(nread, 12);
core.ops.op_close(rid); core.ops.op_close(rid);
assertEquals(await cancel, "resource closed"); assertEquals(await cancelPromise, "resource closed");
}); });
// Close the stream without reading everything // Close the stream without reading everything
Deno.test(async function readableStreamClosePartialRead() { Deno.test(async function readableStreamClosePartialRead() {
const cancel = deferred(); const { promise: cancelPromise, resolve: cancelResolve } = Promise
const rid = resourceForReadableStream(helloWorldStream(false, cancel)); .withResolvers();
const rid = resourceForReadableStream(helloWorldStream(false, cancelResolve));
const buffer = new Uint8Array(5); const buffer = new Uint8Array(5);
const nread = await core.ops.op_read(rid, buffer); const nread = await core.ops.op_read(rid, buffer);
assertEquals(nread, 5); assertEquals(nread, 5);
core.ops.op_close(rid); core.ops.op_close(rid);
assertEquals(await cancel, "resource closed"); assertEquals(await cancelPromise, "resource closed");
}); });
// Close the stream without reading anything // Close the stream without reading anything
Deno.test(async function readableStreamCloseWithoutRead() { Deno.test(async function readableStreamCloseWithoutRead() {
const cancel = deferred(); const { promise: cancelPromise, resolve: cancelResolve } = Promise
const rid = resourceForReadableStream(helloWorldStream(false, cancel)); .withResolvers();
const rid = resourceForReadableStream(helloWorldStream(false, cancelResolve));
core.ops.op_close(rid); core.ops.op_close(rid);
assertEquals(await cancel, "resource closed"); assertEquals(await cancelPromise, "resource closed");
}); });
// Close the stream without reading anything // Close the stream without reading anything
Deno.test(async function readableStreamCloseWithoutRead2() { Deno.test(async function readableStreamCloseWithoutRead2() {
const cancel = deferred(); const { promise: cancelPromise, resolve: cancelResolve } = Promise
const rid = resourceForReadableStream(longAsyncStream(cancel)); .withResolvers();
const rid = resourceForReadableStream(longAsyncStream(cancelResolve));
core.ops.op_close(rid); core.ops.op_close(rid);
assertEquals(await cancel, "resource closed"); assertEquals(await cancelPromise, "resource closed");
}); });
Deno.test(async function readableStreamPartial() { Deno.test(async function readableStreamPartial() {
@ -432,7 +441,8 @@ function createStreamTest(
Deno.test(async function readableStreamWithAggressiveResourceClose() { Deno.test(async function readableStreamWithAggressiveResourceClose() {
let first = true; let first = true;
const reasonPromise = deferred(); const { promise: reasonPromise, resolve: reasonResolve } = Promise
.withResolvers();
const rid = resourceForReadableStream( const rid = resourceForReadableStream(
new ReadableStream({ new ReadableStream({
pull(controller) { pull(controller) {
@ -446,7 +456,7 @@ Deno.test(async function readableStreamWithAggressiveResourceClose() {
} }
}, },
cancel(reason) { cancel(reason) {
reasonPromise.resolve(reason); reasonResolve(reason);
}, },
}), }),
); );

View file

@ -3,20 +3,18 @@ import {
assert, assert,
assertEquals, assertEquals,
assertNotEquals, assertNotEquals,
Deferred,
deferred,
delay, delay,
execCode, execCode,
unreachable, unreachable,
} from "./test_util.ts"; } from "./test_util.ts";
Deno.test(async function functionParameterBindingSuccess() { Deno.test(async function functionParameterBindingSuccess() {
const promise = deferred(); const { promise, resolve } = Promise.withResolvers<void>();
let count = 0; let count = 0;
const nullProto = (newCount: number) => { const nullProto = (newCount: number) => {
count = newCount; count = newCount;
promise.resolve(); resolve();
}; };
Reflect.setPrototypeOf(nullProto, null); Reflect.setPrototypeOf(nullProto, null);
@ -30,10 +28,11 @@ Deno.test(async function functionParameterBindingSuccess() {
Deno.test(async function stringifyAndEvalNonFunctions() { Deno.test(async function stringifyAndEvalNonFunctions() {
// eval can only access global scope // eval can only access global scope
const global = globalThis as unknown as { const global = globalThis as unknown as {
globalPromise: ReturnType<typeof deferred>; globalPromise: ReturnType<typeof Promise.withResolvers<void>>;
globalCount: number; globalCount: number;
}; };
global.globalPromise = deferred();
global.globalPromise = Promise.withResolvers<void>();
global.globalCount = 0; global.globalCount = 0;
const notAFunction = const notAFunction =
@ -42,7 +41,7 @@ Deno.test(async function stringifyAndEvalNonFunctions() {
setTimeout(notAFunction, 500); setTimeout(notAFunction, 500);
await global.globalPromise; await global.globalPromise.promise;
// count should be incremented // count should be incremented
assertEquals(global.globalCount, 1); assertEquals(global.globalCount, 1);
@ -52,11 +51,11 @@ Deno.test(async function stringifyAndEvalNonFunctions() {
}); });
Deno.test(async function timeoutSuccess() { Deno.test(async function timeoutSuccess() {
const promise = deferred(); const { promise, resolve } = Promise.withResolvers<void>();
let count = 0; let count = 0;
setTimeout(() => { setTimeout(() => {
count++; count++;
promise.resolve(); resolve();
}, 500); }, 500);
await promise; await promise;
// count should increment // count should increment
@ -66,9 +65,9 @@ Deno.test(async function timeoutSuccess() {
Deno.test(async function timeoutEvalNoScopeLeak() { Deno.test(async function timeoutEvalNoScopeLeak() {
// eval can only access global scope // eval can only access global scope
const global = globalThis as unknown as { const global = globalThis as unknown as {
globalPromise: Deferred<Error>; globalPromise: ReturnType<typeof Promise.withResolvers<Error>>;
}; };
global.globalPromise = deferred(); global.globalPromise = Promise.withResolvers();
setTimeout( setTimeout(
` `
try { try {
@ -79,16 +78,16 @@ Deno.test(async function timeoutEvalNoScopeLeak() {
}` as unknown as () => void, }` as unknown as () => void,
0, 0,
); );
const error = await global.globalPromise; const error = await global.globalPromise.promise;
assertEquals(error.name, "ReferenceError"); assertEquals(error.name, "ReferenceError");
Reflect.deleteProperty(global, "globalPromise"); Reflect.deleteProperty(global, "globalPromise");
}); });
Deno.test(async function evalPrimordial() { Deno.test(async function evalPrimordial() {
const global = globalThis as unknown as { const global = globalThis as unknown as {
globalPromise: ReturnType<typeof deferred>; globalPromise: ReturnType<typeof Promise.withResolvers<void>>;
}; };
global.globalPromise = deferred(); global.globalPromise = Promise.withResolvers<void>();
const originalEval = globalThis.eval; const originalEval = globalThis.eval;
let wasCalled = false; let wasCalled = false;
globalThis.eval = (argument) => { globalThis.eval = (argument) => {
@ -99,20 +98,20 @@ Deno.test(async function evalPrimordial() {
"globalThis.globalPromise.resolve();" as unknown as () => void, "globalThis.globalPromise.resolve();" as unknown as () => void,
0, 0,
); );
await global.globalPromise; await global.globalPromise.promise;
assert(!wasCalled); assert(!wasCalled);
Reflect.deleteProperty(global, "globalPromise"); Reflect.deleteProperty(global, "globalPromise");
globalThis.eval = originalEval; globalThis.eval = originalEval;
}); });
Deno.test(async function timeoutArgs() { Deno.test(async function timeoutArgs() {
const promise = deferred(); const { promise, resolve } = Promise.withResolvers<void>();
const arg = 1; const arg = 1;
let capturedArgs: unknown[] = []; let capturedArgs: unknown[] = [];
setTimeout( setTimeout(
function () { function () {
capturedArgs = [...arguments]; capturedArgs = [...arguments];
promise.resolve(); resolve();
}, },
10, 10,
arg, arg,
@ -165,13 +164,13 @@ Deno.test(async function timeoutCancelMultiple() {
Deno.test(async function timeoutCancelInvalidSilentFail() { Deno.test(async function timeoutCancelInvalidSilentFail() {
// Expect no panic // Expect no panic
const promise = deferred(); const { promise, resolve } = Promise.withResolvers<void>();
let count = 0; let count = 0;
const id = setTimeout(() => { const id = setTimeout(() => {
count++; count++;
// Should have no effect // Should have no effect
clearTimeout(id); clearTimeout(id);
promise.resolve(); resolve();
}, 500); }, 500);
await promise; await promise;
assertEquals(count, 1); assertEquals(count, 1);
@ -181,12 +180,12 @@ Deno.test(async function timeoutCancelInvalidSilentFail() {
}); });
Deno.test(async function intervalSuccess() { Deno.test(async function intervalSuccess() {
const promise = deferred(); const { promise, resolve } = Promise.withResolvers<void>();
let count = 0; let count = 0;
const id = setInterval(() => { const id = setInterval(() => {
count++; count++;
clearInterval(id); clearInterval(id);
promise.resolve(); resolve();
}, 100); }, 100);
await promise; await promise;
// Clear interval // Clear interval
@ -230,7 +229,7 @@ Deno.test(function intervalCancelInvalidSilentFail() {
}); });
Deno.test(async function callbackTakesLongerThanInterval() { Deno.test(async function callbackTakesLongerThanInterval() {
const promise = deferred(); const { promise, resolve } = Promise.withResolvers<void>();
let timeEndOfFirstCallback: number | undefined; let timeEndOfFirstCallback: number | undefined;
const interval = setInterval(() => { const interval = setInterval(() => {
@ -242,7 +241,7 @@ Deno.test(async function callbackTakesLongerThanInterval() {
// Second callback // Second callback
assert(Date.now() - 100 >= timeEndOfFirstCallback); assert(Date.now() - 100 >= timeEndOfFirstCallback);
clearInterval(interval); clearInterval(interval);
promise.resolve(); resolve();
} }
}, 100); }, 100);
@ -251,10 +250,10 @@ Deno.test(async function callbackTakesLongerThanInterval() {
// https://github.com/denoland/deno/issues/11398 // https://github.com/denoland/deno/issues/11398
Deno.test(async function clearTimeoutAfterNextTimerIsDue1() { Deno.test(async function clearTimeoutAfterNextTimerIsDue1() {
const promise = deferred(); const { promise, resolve } = Promise.withResolvers<void>();
setTimeout(() => { setTimeout(() => {
promise.resolve(); resolve();
}, 300); }, 300);
const interval = setInterval(() => { const interval = setInterval(() => {
@ -268,12 +267,12 @@ Deno.test(async function clearTimeoutAfterNextTimerIsDue1() {
// https://github.com/denoland/deno/issues/11398 // https://github.com/denoland/deno/issues/11398
Deno.test(async function clearTimeoutAfterNextTimerIsDue2() { Deno.test(async function clearTimeoutAfterNextTimerIsDue2() {
const promise = deferred(); const { promise, resolve } = Promise.withResolvers<void>();
const timeout1 = setTimeout(unreachable, 100); const timeout1 = setTimeout(unreachable, 100);
setTimeout(() => { setTimeout(() => {
promise.resolve(); resolve();
}, 200); }, 200);
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 300); Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 300);
@ -293,12 +292,12 @@ Deno.test(async function fireCallbackImmediatelyWhenDelayOverMaxValue() {
}); });
Deno.test(async function timeoutCallbackThis() { Deno.test(async function timeoutCallbackThis() {
const promise = deferred(); const { promise, resolve } = Promise.withResolvers<void>();
let capturedThis: unknown; let capturedThis: unknown;
const obj = { const obj = {
foo() { foo() {
capturedThis = this; capturedThis = this;
promise.resolve(); resolve();
}, },
}; };
setTimeout(obj.foo, 1); setTimeout(obj.foo, 1);
@ -322,10 +321,10 @@ Deno.test(async function timeoutBindThis() {
]; ];
for (const thisArg of thisCheckPassed) { for (const thisArg of thisCheckPassed) {
const resolvable = deferred(); const { promise, resolve } = Promise.withResolvers<void>();
let hasThrown = 0; let hasThrown = 0;
try { try {
setTimeout.call(thisArg, () => resolvable.resolve(), 1); setTimeout.call(thisArg, () => resolve(), 1);
hasThrown = 1; hasThrown = 1;
} catch (err) { } catch (err) {
if (err instanceof TypeError) { if (err instanceof TypeError) {
@ -334,7 +333,7 @@ Deno.test(async function timeoutBindThis() {
hasThrown = 3; hasThrown = 3;
} }
} }
await resolvable; await promise;
assertEquals(hasThrown, 1); assertEquals(hasThrown, 1);
} }
@ -414,12 +413,12 @@ Deno.test(function clearTimeoutAndClearIntervalNotBeEquals() {
Deno.test(async function timerOrdering() { Deno.test(async function timerOrdering() {
const array: number[] = []; const array: number[] = [];
const donePromise = deferred(); const { promise: donePromise, resolve } = Promise.withResolvers<void>();
function push(n: number) { function push(n: number) {
array.push(n); array.push(n);
if (array.length === 6) { if (array.length === 6) {
donePromise.resolve(); resolve();
} }
} }
@ -444,13 +443,13 @@ Deno.test(async function timerOrdering() {
Deno.test(async function timerBasicMicrotaskOrdering() { Deno.test(async function timerBasicMicrotaskOrdering() {
let s = ""; let s = "";
let count = 0; let count = 0;
const promise = deferred(); const { promise, resolve } = Promise.withResolvers<void>();
setTimeout(() => { setTimeout(() => {
Promise.resolve().then(() => { Promise.resolve().then(() => {
count++; count++;
s += "de"; s += "de";
if (count === 2) { if (count === 2) {
promise.resolve(); resolve();
} }
}); });
}); });
@ -458,7 +457,7 @@ Deno.test(async function timerBasicMicrotaskOrdering() {
count++; count++;
s += "no"; s += "no";
if (count === 2) { if (count === 2) {
promise.resolve(); resolve();
} }
}); });
await promise; await promise;
@ -467,7 +466,7 @@ Deno.test(async function timerBasicMicrotaskOrdering() {
Deno.test(async function timerNestedMicrotaskOrdering() { Deno.test(async function timerNestedMicrotaskOrdering() {
let s = ""; let s = "";
const promise = deferred(); const { promise, resolve } = Promise.withResolvers<void>();
s += "0"; s += "0";
setTimeout(() => { setTimeout(() => {
s += "4"; s += "4";
@ -476,7 +475,7 @@ Deno.test(async function timerNestedMicrotaskOrdering() {
.then(() => { .then(() => {
setTimeout(() => { setTimeout(() => {
s += "B"; s += "B";
promise.resolve(); resolve();
}); });
}) })
.then(() => { .then(() => {
@ -507,11 +506,11 @@ Deno.test(function testQueueMicrotask() {
Deno.test(async function timerIgnoresDateOverride() { Deno.test(async function timerIgnoresDateOverride() {
const OriginalDate = Date; const OriginalDate = Date;
const promise = deferred(); const { promise, resolve, reject } = Promise.withResolvers<void>();
let hasThrown = 0; let hasThrown = 0;
try { try {
const overrideCalled: () => number = () => { const overrideCalled: () => number = () => {
promise.reject("global Date override used over original Date object"); reject("global Date override used over original Date object");
return 0; return 0;
}; };
const DateOverride = () => { const DateOverride = () => {
@ -521,7 +520,9 @@ Deno.test(async function timerIgnoresDateOverride() {
globalThis.Date.now = overrideCalled; globalThis.Date.now = overrideCalled;
globalThis.Date.UTC = overrideCalled; globalThis.Date.UTC = overrideCalled;
globalThis.Date.parse = overrideCalled; globalThis.Date.parse = overrideCalled;
queueMicrotask(promise.resolve); queueMicrotask(() => {
resolve();
});
await promise; await promise;
hasThrown = 1; hasThrown = 1;
} catch (err) { } catch (err) {
@ -748,11 +749,11 @@ Deno.test({
Deno.test({ Deno.test({
name: "regression for #20367", name: "regression for #20367",
fn: async () => { fn: async () => {
const promise = deferred<number>(); const { promise, resolve } = Promise.withResolvers<number>();
const start = performance.now(); const start = performance.now();
setTimeout(() => { setTimeout(() => {
const end = performance.now(); const end = performance.now();
promise.resolve(end - start); resolve(end - start);
}, 1000); }, 1000);
clearTimeout(setTimeout(() => {}, 1000)); clearTimeout(setTimeout(() => {}, 1000));

View file

@ -1,10 +1,10 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
import { assertEquals, deferred } from "./test_util.ts"; import { assertEquals } from "./test_util.ts";
Deno.test( Deno.test(
{ permissions: { env: true, read: true } }, { permissions: { env: true, read: true } },
async function workerEnvArrayPermissions() { async function workerEnvArrayPermissions() {
const promise = deferred<boolean[]>(); const { promise, resolve } = Promise.withResolvers<boolean[]>();
const worker = new Worker( const worker = new Worker(
import.meta.resolve( import.meta.resolve(
@ -14,7 +14,7 @@ Deno.test(
); );
worker.onmessage = ({ data }) => { worker.onmessage = ({ data }) => {
promise.resolve(data.permissions); resolve(data.permissions);
}; };
worker.postMessage({ worker.postMessage({