1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-11-21 15:04:11 -05:00

refactor: replace deferred() from std/async with Promise.withResolvers() (#21234)

Closes #21041

---------

Signed-off-by: Asher Gomez <ashersaupingomez@gmail.com>
This commit is contained in:
Asher Gomez 2023-11-22 22:11:20 +11:00 committed by GitHub
parent 0ffcb46e0f
commit 616354e76c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
35 changed files with 952 additions and 1020 deletions

View file

@ -1,4 +1,3 @@
import { deferred } from "../../../../test_util/std/async/deferred.ts";
import {
assert,
assertEquals,
@ -9,7 +8,7 @@ import { TextProtoReader } from "./textproto.ts";
const encoder = new TextEncoder();
const decoder = new TextDecoder();
const resolvable = deferred();
const { promise, resolve } = Promise.withResolvers();
const hostname = "localhost";
const port = 3505;
@ -32,7 +31,7 @@ listener.accept().then(
// TODO(bartlomieju): this might be a bug
setTimeout(() => {
conn.close();
resolvable.resolve();
resolve();
}, 0);
},
);
@ -65,6 +64,6 @@ await r.readFull(bodyBuf);
assertEquals(decoder.decode(bodyBuf), "Hello World\n");
conn.close();
listener.close();
await resolvable;
await promise;
console.log("DONE");

View file

@ -1,4 +1,3 @@
import { deferred } from "../../../../test_util/std/async/deferred.ts";
import {
assert,
assertEquals,
@ -10,7 +9,7 @@ import { TextProtoReader } from "./textproto.ts";
const encoder = new TextEncoder();
const decoder = new TextDecoder();
const resolvable = deferred();
const { promise, resolve } = Promise.withResolvers();
const hostname = "localhost";
const port = 3504;
@ -33,7 +32,7 @@ listener.accept().then(
// TODO(bartlomieju): this might be a bug
setTimeout(() => {
conn.close();
resolvable.resolve();
resolve();
}, 0);
},
);
@ -64,6 +63,6 @@ await r.readFull(bodyBuf);
assertEquals(decoder.decode(bodyBuf), "Hello World\n");
conn.close();
listener.close();
await resolvable;
await promise;
console.log("DONE");

View file

@ -1,8 +1,7 @@
import { assertEquals } from "../../../../test_util/std/testing/asserts.ts";
import { deferred } from "../../../../test_util/std/async/deferred.ts";
const errorDeferred = deferred();
const closeDeferred = deferred();
const errorDeferred = Promise.withResolvers<void>();
const closeDeferred = Promise.withResolvers<void>();
const listener = Deno.listen({ port: 4509 });
console.log("READY");
@ -21,6 +20,6 @@ socket.onclose = (e) => {
};
await respondWith(response);
await errorDeferred;
await closeDeferred;
await errorDeferred.promise;
await closeDeferred.promise;
listener.close();

View file

@ -1,6 +1,4 @@
import { deferred } from "../../unit/test_util.ts";
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
const listener = Deno.listen({ port: 4319 });
console.log("READY");
const conn = await listener.accept();
@ -12,6 +10,6 @@ const {
} = Deno.upgradeWebSocket(request);
socket.onerror = () => Deno.exit(1);
socket.onopen = () => socket.close();
socket.onclose = () => promise.resolve();
socket.onclose = () => resolve();
await respondWith(response);
await promise;

View file

@ -5,7 +5,6 @@ import {
assertThrows,
fail,
} from "../../../../test_util/std/testing/asserts.ts";
import { deferred } from "../../../../test_util/std/async/deferred.ts";
Deno.test("invalid scheme", () => {
assertThrows(() => new WebSocket("foo://localhost:4242"));
@ -21,7 +20,7 @@ Deno.test("duplicate protocols", () => {
});
Deno.test("invalid server", async () => {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
const ws = new WebSocket("ws://localhost:2121");
let err = false;
ws.onerror = () => {
@ -29,7 +28,7 @@ Deno.test("invalid server", async () => {
};
ws.onclose = () => {
if (err) {
promise.resolve();
resolve();
} else {
fail();
}
@ -39,20 +38,20 @@ Deno.test("invalid server", async () => {
});
Deno.test("connect & close", async () => {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
const ws = new WebSocket("ws://localhost:4242");
ws.onerror = () => fail();
ws.onopen = () => {
ws.close();
};
ws.onclose = () => {
promise.resolve();
resolve();
};
await promise;
});
Deno.test("connect & abort", async () => {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
const ws = new WebSocket("ws://localhost:4242");
ws.close();
let err = false;
@ -61,7 +60,7 @@ Deno.test("connect & abort", async () => {
};
ws.onclose = () => {
if (err) {
promise.resolve();
resolve();
} else {
fail();
}
@ -71,18 +70,18 @@ Deno.test("connect & abort", async () => {
});
Deno.test("connect & close custom valid code", async () => {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
const ws = new WebSocket("ws://localhost:4242");
ws.onerror = () => fail();
ws.onopen = () => ws.close(1000);
ws.onclose = () => {
promise.resolve();
resolve();
};
await promise;
});
Deno.test("connect & close custom invalid code", async () => {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
const ws = new WebSocket("ws://localhost:4242");
ws.onerror = () => fail();
ws.onopen = () => {
@ -90,24 +89,24 @@ Deno.test("connect & close custom invalid code", async () => {
ws.close();
};
ws.onclose = () => {
promise.resolve();
resolve();
};
await promise;
});
Deno.test("connect & close custom valid reason", async () => {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
const ws = new WebSocket("ws://localhost:4242");
ws.onerror = () => fail();
ws.onopen = () => ws.close(1000, "foo");
ws.onclose = () => {
promise.resolve();
resolve();
};
await promise;
});
Deno.test("connect & close custom invalid reason", async () => {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
const ws = new WebSocket("ws://localhost:4242");
ws.onerror = () => fail();
ws.onopen = () => {
@ -115,13 +114,13 @@ Deno.test("connect & close custom invalid reason", async () => {
ws.close();
};
ws.onclose = () => {
promise.resolve();
resolve();
};
await promise;
});
Deno.test("echo string", async () => {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
const ws = new WebSocket("ws://localhost:4242");
ws.onerror = () => fail();
ws.onopen = () => ws.send("foo");
@ -130,31 +129,31 @@ Deno.test("echo string", async () => {
ws.close();
};
ws.onclose = () => {
promise.resolve();
resolve();
};
await promise;
});
Deno.test("echo string tls", async () => {
const promise1 = deferred();
const promise2 = deferred();
const deferred1 = Promise.withResolvers<void>();
const deferred2 = Promise.withResolvers<void>();
const ws = new WebSocket("wss://localhost:4243");
ws.onerror = () => fail();
ws.onopen = () => ws.send("foo");
ws.onmessage = (e) => {
assertEquals(e.data, "foo");
ws.close();
promise1.resolve();
deferred1.resolve();
};
ws.onclose = () => {
promise2.resolve();
deferred2.resolve();
};
await promise1;
await promise2;
await deferred1.promise;
await deferred2.promise;
});
Deno.test("websocket error", async () => {
const promise1 = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
const ws = new WebSocket("wss://localhost:4242");
ws.onopen = () => fail();
ws.onerror = (err) => {
@ -163,13 +162,13 @@ Deno.test("websocket error", async () => {
err.message,
"NetworkError: failed to connect to WebSocket: received corrupt message of type InvalidContentType",
);
promise1.resolve();
resolve();
};
await promise1;
await promise;
});
Deno.test("echo blob with binaryType blob", async () => {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
const ws = new WebSocket("ws://localhost:4242");
const blob = new Blob(["foo"]);
ws.onerror = () => fail();
@ -183,13 +182,13 @@ Deno.test("echo blob with binaryType blob", async () => {
ws.close();
};
ws.onclose = () => {
promise.resolve();
resolve();
};
await promise;
});
Deno.test("echo blob with binaryType arraybuffer", async () => {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
const ws = new WebSocket("ws://localhost:4242");
ws.binaryType = "arraybuffer";
const blob = new Blob(["foo"]);
@ -202,13 +201,13 @@ Deno.test("echo blob with binaryType arraybuffer", async () => {
ws.close();
};
ws.onclose = () => {
promise.resolve();
resolve();
};
await promise;
});
Deno.test("echo uint8array with binaryType blob", async () => {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
const ws = new WebSocket("ws://localhost:4242");
const uint = new Uint8Array([102, 111, 111]);
ws.onerror = () => fail();
@ -220,13 +219,13 @@ Deno.test("echo uint8array with binaryType blob", async () => {
ws.close();
};
ws.onclose = () => {
promise.resolve();
resolve();
};
await promise;
});
Deno.test("echo uint8array with binaryType arraybuffer", async () => {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
const ws = new WebSocket("ws://localhost:4242");
ws.binaryType = "arraybuffer";
const uint = new Uint8Array([102, 111, 111]);
@ -237,13 +236,13 @@ Deno.test("echo uint8array with binaryType arraybuffer", async () => {
ws.close();
};
ws.onclose = () => {
promise.resolve();
resolve();
};
await promise;
});
Deno.test("echo arraybuffer with binaryType blob", async () => {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
const ws = new WebSocket("ws://localhost:4242");
const buffer = new ArrayBuffer(3);
ws.onerror = () => fail();
@ -255,13 +254,13 @@ Deno.test("echo arraybuffer with binaryType blob", async () => {
ws.close();
};
ws.onclose = () => {
promise.resolve();
resolve();
};
await promise;
});
Deno.test("echo arraybuffer with binaryType arraybuffer", async () => {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
const ws = new WebSocket("ws://localhost:4242");
ws.binaryType = "arraybuffer";
const buffer = new ArrayBuffer(3);
@ -272,13 +271,13 @@ Deno.test("echo arraybuffer with binaryType arraybuffer", async () => {
ws.close();
};
ws.onclose = () => {
promise.resolve();
resolve();
};
await promise;
});
Deno.test("Event Handlers order", async () => {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
const ws = new WebSocket("ws://localhost:4242");
const arr: number[] = [];
ws.onerror = () => fail();
@ -292,18 +291,18 @@ Deno.test("Event Handlers order", async () => {
ws.onmessage = () => arr.push(2);
ws.onopen = () => ws.send("Echo");
ws.onclose = () => {
promise.resolve();
resolve();
};
await promise;
});
Deno.test("Close without frame", async () => {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
const ws = new WebSocket("ws://localhost:4244");
ws.onerror = () => fail();
ws.onclose = (e) => {
assertEquals(e.code, 1005);
promise.resolve();
resolve();
};
await promise;
});

View file

@ -68,7 +68,7 @@ error: Started test step with sanitizers while another test step was running:
FAILURES
capturing => ./test/steps/invalid_usage.ts:3:6
capturing => ./test/steps/invalid_usage.ts:1:6
top level missing await ... step => ./test/steps/invalid_usage.ts:[WILDCARD]
inner missing await ... step ... inner => ./test/steps/invalid_usage.ts:[WILDCARD]
parallel steps with sanitizers ... step 2 => ./test/steps/invalid_usage.ts:[WILDCARD]

View file

@ -1,5 +1,3 @@
import { deferred } from "../../../../../test_util/std/async/deferred.ts";
Deno.test("capturing", async (t) => {
let capturedContext!: Deno.TestContext;
await t.step("some step", (t) => {
@ -32,27 +30,27 @@ Deno.test({
Deno.test("parallel steps with sanitizers", async (t) => {
// not allowed because steps with sanitizers cannot be run in parallel
const step1Entered = deferred();
const testFinished = deferred();
const step1Entered = Promise.withResolvers<void>();
const testFinished = Promise.withResolvers<void>();
t.step("step 1", async () => {
step1Entered.resolve();
await testFinished;
await testFinished.promise;
});
await step1Entered;
await step1Entered.promise;
await t.step("step 2", () => {});
});
Deno.test("parallel steps when first has sanitizer", async (t) => {
const step1Entered = deferred();
const step2Finished = deferred();
const step1Entered = Promise.withResolvers<void>();
const step2Finished = Promise.withResolvers<void>();
const step1 = t.step({
name: "step 1",
fn: async () => {
step1Entered.resolve();
await step2Finished;
await step2Finished.promise;
},
});
await step1Entered;
await step1Entered.promise;
await t.step({
name: "step 2",
fn: () => {},
@ -65,19 +63,19 @@ Deno.test("parallel steps when first has sanitizer", async (t) => {
});
Deno.test("parallel steps when second has sanitizer", async (t) => {
const step1Entered = deferred();
const step2Finished = deferred();
const step1Entered = Promise.withResolvers<void>();
const step2Finished = Promise.withResolvers<void>();
const step1 = t.step({
name: "step 1",
fn: async () => {
step1Entered.resolve();
await step2Finished;
await step2Finished.promise;
},
sanitizeOps: false,
sanitizeResources: false,
sanitizeExit: false,
});
await step1Entered;
await step1Entered.promise;
await t.step({
name: "step 2",
fn: async () => {
@ -91,19 +89,19 @@ Deno.test("parallel steps when second has sanitizer", async (t) => {
Deno.test({
name: "parallel steps where only inner tests have sanitizers",
fn: async (t) => {
const step1Entered = deferred();
const step2Finished = deferred();
const step1Entered = Promise.withResolvers<void>();
const step2Finished = Promise.withResolvers<void>();
const step1 = t.step("step 1", async (t) => {
await t.step({
name: "step inner",
fn: async () => {
step1Entered.resolve();
await step2Finished;
await step2Finished.promise;
},
sanitizeOps: true,
});
});
await step1Entered;
await step1Entered.promise;
await t.step("step 2", async (t) => {
await t.step({
name: "step inner",

View file

@ -1,5 +1,3 @@
import { deferred } from "../../../../../test_util/std/async/deferred.ts";
Deno.test("description", async (t) => {
const success = await t.step("step 1", async (t) => {
await t.step("inner 1", () => {});
@ -107,9 +105,9 @@ Deno.test("steps buffered then streaming reporting", async (t) => {
name: "step 1",
fn: async (t) => {
// also ensure the buffered tests display in order regardless of the second one finishing first
const step2Finished = deferred();
const step2Finished = Promise.withResolvers<void>();
const step1 = t.step("step 1 - 1", async () => {
await step2Finished;
await step2Finished.promise;
});
const step2 = t.step("step 1 - 2", async (t) => {
await t.step("step 1 - 2 - 1", () => {});

View file

@ -5,13 +5,8 @@ const data = "HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello World\n";
const workerCount = 4;
const cmdsPerWorker = 400;
import {
Deferred,
deferred,
} from "../../../../test_util/std/async/deferred.ts";
function handleAsyncMsgFromWorker(
promiseTable: Map<number, Deferred<string>>,
promiseTable: Map<number, ReturnType<typeof Promise.withResolvers<string>>>,
msg: { cmdId: number; data: string },
) {
const promise = promiseTable.get(msg.cmdId);
@ -22,15 +17,17 @@ function handleAsyncMsgFromWorker(
}
async function main() {
const workers: Array<[Map<number, Deferred<string>>, Worker]> = [];
const workers: Array<
[Map<number, ReturnType<typeof Promise.withResolvers<string>>>, Worker]
> = [];
for (let i = 1; i <= workerCount; ++i) {
const worker = new Worker(
import.meta.resolve("./bench_worker.ts"),
{ type: "module" },
);
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
worker.onmessage = (e) => {
if (e.data.cmdId === 0) promise.resolve();
if (e.data.cmdId === 0) resolve();
};
worker.postMessage({ cmdId: 0, action: 2 });
await promise;
@ -45,19 +42,19 @@ async function main() {
for (const cmdId of Array(cmdsPerWorker).keys()) {
const promises: Array<Promise<string>> = [];
for (const [promiseTable, worker] of workers) {
const promise = deferred<string>();
promiseTable.set(cmdId, promise);
const deferred = Promise.withResolvers<string>();
promiseTable.set(cmdId, deferred);
worker.postMessage({ cmdId: cmdId, action: 1, data });
promises.push(promise);
promises.push(deferred.promise);
}
for (const promise of promises) {
await promise;
}
}
for (const [, worker] of workers) {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
worker.onmessage = (e) => {
if (e.data.cmdId === 3) promise.resolve();
if (e.data.cmdId === 3) resolve();
};
worker.postMessage({ action: 3 });
await promise;

View file

@ -8,7 +8,6 @@ import {
assertMatch,
assertThrows,
} from "../../../../test_util/std/testing/asserts.ts";
import { deferred } from "../../../../test_util/std/async/deferred.ts";
Deno.test({
name: "worker terminate",
@ -22,20 +21,20 @@ Deno.test({
{ type: "module", name: "tsWorker" },
);
const promise1 = deferred();
const deferred1 = Promise.withResolvers<string>();
jsWorker.onmessage = (e) => {
promise1.resolve(e.data);
deferred1.resolve(e.data);
};
const promise2 = deferred();
const deferred2 = Promise.withResolvers<string>();
tsWorker.onmessage = (e) => {
promise2.resolve(e.data);
deferred2.resolve(e.data);
};
jsWorker.postMessage("Hello World");
assertEquals(await promise1, "Hello World");
assertEquals(await deferred1.promise, "Hello World");
tsWorker.postMessage("Hello World");
assertEquals(await promise2, "Hello World");
assertEquals(await deferred2.promise, "Hello World");
tsWorker.terminate();
jsWorker.terminate();
},
@ -49,9 +48,9 @@ Deno.test({
{ type: "module", name: "tsWorker" },
);
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<string>();
tsWorker.onmessage = (e) => {
promise.resolve(e.data);
resolve(e.data);
};
tsWorker.postMessage("Hello World");
@ -68,9 +67,10 @@ Deno.test({
{ type: "module", name: "nested" },
);
const promise = deferred();
// deno-lint-ignore no-explicit-any
const { promise, resolve } = Promise.withResolvers<any>();
nestedWorker.onmessage = (e) => {
promise.resolve(e.data);
resolve(e.data);
};
nestedWorker.postMessage("Hello World");
@ -87,11 +87,11 @@ Deno.test({
{ type: "module" },
);
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<string>();
// deno-lint-ignore no-explicit-any
throwingWorker.onerror = (e: any) => {
e.preventDefault();
promise.resolve(e.message);
resolve(e.message);
};
assertMatch(await promise as string, /Uncaught Error: Thrown error/);
@ -108,9 +108,9 @@ Deno.test({
workerOptions,
);
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<string>();
w.onmessage = (e) => {
promise.resolve(e.data);
resolve(e.data);
};
w.postMessage("Hello, world!");
@ -128,9 +128,9 @@ Deno.test({
workerOptions,
);
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<string>();
w.onmessage = (e) => {
promise.resolve(e.data);
resolve(e.data);
};
w.postMessage("Hello, world!");
@ -147,15 +147,15 @@ Deno.test({
{ type: "module" },
);
const promise = deferred();
const { promise, resolve, reject } = Promise.withResolvers<string>();
// deno-lint-ignore no-explicit-any
fetchingWorker.onerror = (e: any) => {
e.preventDefault();
promise.reject(e.message);
reject(e.message);
};
// Defer promise.resolve() to allow worker to shut down
fetchingWorker.onmessage = (e) => {
promise.resolve(e.data);
resolve(e.data);
};
assertEquals(await promise, "Done!");
@ -166,7 +166,7 @@ Deno.test({
Deno.test({
name: "worker terminate busy loop",
fn: async function () {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<number>();
const busyWorker = new Worker(
import.meta.resolve("./busy_worker.js"),
@ -183,7 +183,7 @@ Deno.test({
throw new Error("unreachable");
};
setTimeout(() => {
promise.resolve(testResult);
resolve(testResult);
}, 100);
}
};
@ -198,7 +198,7 @@ Deno.test({
fn: async function () {
// See issue for details
// https://github.com/denoland/deno/issues/4080
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
const racyWorker = new Worker(
import.meta.resolve("./racy_worker.js"),
@ -207,7 +207,7 @@ Deno.test({
racyWorker.onmessage = (_e) => {
setTimeout(() => {
promise.resolve();
resolve();
}, 100);
};
@ -222,8 +222,8 @@ Deno.test({
let messageHandlersCalled = 0;
let errorHandlersCalled = 0;
const promise1 = deferred();
const promise2 = deferred();
const deferred1 = Promise.withResolvers<void>();
const deferred2 = Promise.withResolvers<void>();
const worker = new Worker(
import.meta.resolve("./event_worker.js"),
@ -238,7 +238,7 @@ Deno.test({
});
worker.addEventListener("message", (_e: Event) => {
messageHandlersCalled++;
promise1.resolve();
deferred1.resolve();
});
worker.onerror = (e) => {
@ -250,15 +250,15 @@ Deno.test({
});
worker.addEventListener("error", (_e: Event) => {
errorHandlersCalled++;
promise2.resolve();
deferred2.resolve();
});
worker.postMessage("ping");
await promise1;
await deferred1.promise;
assertEquals(messageHandlersCalled, 3);
worker.postMessage("boom");
await promise2;
await deferred2.promise;
assertEquals(errorHandlersCalled, 3);
worker.terminate();
},
@ -272,9 +272,10 @@ Deno.test({
{ type: "module" },
);
const promise = deferred();
// deno-lint-ignore no-explicit-any
const { promise, resolve } = Promise.withResolvers<any>();
worker.onmessage = (e: MessageEvent) => {
promise.resolve(e.data);
resolve(e.data);
};
worker.onerror = (_e) => {
throw new Error("unreachable");
@ -298,10 +299,10 @@ Deno.test({
{ type: "module", deno: { permissions: "inherit" } },
);
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<string>();
denoWorker.onmessage = (e) => {
denoWorker.terminate();
promise.resolve(e.data);
resolve(e.data);
};
denoWorker.postMessage("Hello World");
@ -317,9 +318,9 @@ Deno.test({
{ type: "module" },
);
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<boolean>();
w.onmessage = (e) => {
promise.resolve(e.data);
resolve(e.data);
};
w.postMessage(null);
@ -331,7 +332,7 @@ Deno.test({
Deno.test({
name: "Worker event handler order",
fn: async function () {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
const w = new Worker(
import.meta.resolve("./test_worker.ts"),
{ type: "module", name: "tsWorker" },
@ -343,7 +344,7 @@ Deno.test({
};
w.addEventListener("message", () => arr.push(3));
w.addEventListener("message", () => {
promise.resolve();
resolve();
});
w.postMessage("Hello World");
await promise;
@ -355,13 +356,13 @@ Deno.test({
Deno.test({
name: "Worker immediate close",
fn: async function () {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
const w = new Worker(
import.meta.resolve("./immediately_close_worker.js"),
{ type: "module" },
);
setTimeout(() => {
promise.resolve();
resolve();
}, 1000);
await promise;
w.terminate();
@ -371,7 +372,7 @@ Deno.test({
Deno.test({
name: "Worker post undefined",
fn: async function () {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
const worker = new Worker(
import.meta.resolve("./post_undefined.ts"),
{ type: "module" },
@ -380,7 +381,7 @@ Deno.test({
const handleWorkerMessage = (e: MessageEvent) => {
console.log("main <- worker:", e.data);
worker.terminate();
promise.resolve();
resolve();
};
worker.addEventListener("messageerror", () => console.log("message error"));
@ -399,9 +400,9 @@ Deno.test("Worker inherits permissions", async function () {
{ type: "module", deno: { permissions: "inherit" } },
);
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<boolean>();
worker.onmessage = (e) => {
promise.resolve(e.data);
resolve(e.data);
};
worker.postMessage(null);
@ -415,9 +416,9 @@ Deno.test("Worker limit children permissions", async function () {
{ type: "module", deno: { permissions: { read: false } } },
);
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<boolean>();
worker.onmessage = (e) => {
promise.resolve(e.data);
resolve(e.data);
};
worker.postMessage(null);
@ -443,8 +444,9 @@ Deno.test("Worker limit children permissions granularly", async function () {
},
},
);
const promise = deferred();
worker.onmessage = ({ data }) => promise.resolve(data);
// deno-lint-ignore no-explicit-any
const { promise, resolve } = Promise.withResolvers<any>();
worker.onmessage = ({ data }) => resolve(data);
assertEquals(await promise, {
envGlobal: "prompt",
envFoo: "granted",
@ -482,8 +484,9 @@ Deno.test("Nested worker limit children permissions", async function () {
import.meta.resolve("./parent_read_check_worker.js"),
{ type: "module", deno: { permissions: "inherit" } },
);
const promise = deferred();
worker.onmessage = ({ data }) => promise.resolve(data);
// deno-lint-ignore no-explicit-any
const { promise, resolve } = Promise.withResolvers<any>();
worker.onmessage = ({ data }) => resolve(data);
assertEquals(await promise, {
envGlobal: "prompt",
envFoo: "prompt",
@ -541,9 +544,9 @@ Deno.test("Worker with disabled permissions", async function () {
{ type: "module", deno: { permissions: "none" } },
);
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<boolean>();
worker.onmessage = (e) => {
promise.resolve(e.data);
resolve(e.data);
};
worker.postMessage(null);
@ -557,9 +560,10 @@ Deno.test("Worker permissions are not inherited with empty permission object", a
{ type: "module", deno: { permissions: {} } },
);
const promise = deferred();
// deno-lint-ignore no-explicit-any
const { promise, resolve } = Promise.withResolvers<any>();
worker.onmessage = (e) => {
promise.resolve(e.data);
resolve(e.data);
};
worker.postMessage(null);
@ -581,9 +585,10 @@ Deno.test("Worker permissions are not inherited with single specified permission
{ type: "module", deno: { permissions: { net: true } } },
);
const promise = deferred();
// deno-lint-ignore no-explicit-any
const { promise, resolve } = Promise.withResolvers<any>();
worker.onmessage = (e) => {
promise.resolve(e.data);
resolve(e.data);
};
worker.postMessage(null);
@ -615,11 +620,11 @@ Deno.test("Worker with invalid permission arg", function () {
Deno.test({
name: "worker location",
fn: async function () {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<string>();
const workerModuleHref = import.meta.resolve("./worker_location.ts");
const w = new Worker(workerModuleHref, { type: "module" });
w.onmessage = (e) => {
promise.resolve(e.data);
resolve(e.data);
};
w.postMessage("Hello, world!");
assertEquals(await promise, `${workerModuleHref}, true`);
@ -635,9 +640,9 @@ Deno.test({
"./workers/test_worker.ts",
{ type: "module", name: "tsWorker" },
);
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<string>();
w.onmessage = (e) => {
promise.resolve(e.data);
resolve(e.data);
};
w.postMessage("Hello, world!");
assertEquals(await promise, "Hello, world!");
@ -648,7 +653,7 @@ Deno.test({
Deno.test({
name: "Worker with top-level-await",
fn: async function () {
const result = deferred();
const { promise, resolve, reject } = Promise.withResolvers<void>();
const worker = new Worker(
import.meta.resolve("./worker_with_top_level_await.ts"),
{ type: "module" },
@ -657,12 +662,12 @@ Deno.test({
if (e.data == "ready") {
worker.postMessage("trigger worker handler");
} else if (e.data == "triggered worker handler") {
result.resolve();
resolve();
} else {
result.reject(new Error("Handler didn't run during top-level delay."));
reject(new Error("Handler didn't run during top-level delay."));
}
};
await result;
await promise;
worker.terminate();
},
});
@ -670,15 +675,15 @@ Deno.test({
Deno.test({
name: "Worker with native HTTP",
fn: async function () {
const result = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
const worker = new Worker(
import.meta.resolve("./http_worker.js"),
{ type: "module", deno: { permissions: "inherit" } },
);
worker.onmessage = () => {
result.resolve();
resolve();
};
await result;
await promise;
assert(worker);
const response = await fetch("http://localhost:4506");
@ -695,14 +700,14 @@ Deno.test({
{ type: "module" },
);
const result = deferred();
// deno-lint-ignore no-explicit-any
const { promise, resolve } = Promise.withResolvers<any>();
worker.onmessage = (e) => {
result.resolve(e.data);
resolve(e.data);
};
worker.postMessage("START");
// deno-lint-ignore no-explicit-any
const data = await result as any;
const data = await promise;
// self field should reference itself (circular ref)
assert(data === data.self);
// fields a and b refer to the same array
@ -729,9 +734,9 @@ Deno.test({
"./workers/test_worker.ts",
{ type: "module", name: "tsWorker" },
);
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<string>();
w.onmessage = (e) => {
promise.resolve(e.data);
resolve(e.data);
};
w.postMessage("Hello, world!");
assertEquals(await promise, "Hello, world!");
@ -742,7 +747,7 @@ Deno.test({
Deno.test({
name: "worker SharedArrayBuffer",
fn: async function () {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
const workerOptions: WorkerOptions = { type: "module" };
const w = new Worker(
import.meta.resolve("./shared_array_buffer.ts"),
@ -757,7 +762,7 @@ Deno.test({
w.onmessage = () => {
w.postMessage([sab1, sab2]);
w.onmessage = () => {
promise.resolve();
resolve();
};
};
await promise;
@ -776,30 +781,31 @@ Deno.test({
);
const channel = new MessageChannel();
const promise1 = deferred();
const promise2 = deferred();
const promise3 = deferred();
const result = deferred();
// deno-lint-ignore no-explicit-any
const deferred1 = Promise.withResolvers<any>();
const deferred2 = Promise.withResolvers<boolean>();
const deferred3 = Promise.withResolvers<boolean>();
const result = Promise.withResolvers<void>();
worker.onmessage = (e) => {
promise1.resolve([e.data, e.ports.length]);
deferred1.resolve([e.data, e.ports.length]);
const port1 = e.ports[0];
port1.onmessage = (e) => {
promise2.resolve(e.data);
deferred2.resolve(e.data);
port1.close();
worker.postMessage("3", [channel.port1]);
};
port1.postMessage("2");
};
channel.port2.onmessage = (e) => {
promise3.resolve(e.data);
deferred3.resolve(e.data);
channel.port2.close();
result.resolve();
};
assertEquals(await promise1, ["1", 1]);
assertEquals(await promise2, true);
assertEquals(await promise3, true);
await result;
assertEquals(await deferred1.promise, ["1", 1]);
assertEquals(await deferred2.promise, true);
assertEquals(await deferred3.promise, true);
await result.promise;
worker.terminate();
},
});
@ -818,14 +824,15 @@ Deno.test({
w.postMessage(null);
const memoryUsagePromise = deferred();
// deno-lint-ignore no-explicit-any
const { promise, resolve } = Promise.withResolvers<any>();
w.onmessage = function (evt) {
memoryUsagePromise.resolve(evt.data);
resolve(evt.data);
};
assertEquals(
Object.keys(
await memoryUsagePromise as unknown as Record<string, number>,
await promise as unknown as Record<string, number>,
),
["rss", "heapTotal", "heapUsed", "external"],
);

View file

@ -8,7 +8,6 @@ import {
assertRejects,
assertStrictEquals,
assertThrows,
deferred,
delay,
fail,
} from "./test_util.ts";
@ -592,9 +591,9 @@ Deno.test(
let counter = 0;
const deferreds = [
deferred(),
deferred(),
deferred(),
Promise.withResolvers<void>(),
Promise.withResolvers<void>(),
Promise.withResolvers<void>(),
];
async function writeRequest(conn: Deno.Conn) {
@ -639,7 +638,7 @@ Deno.test(
return controller.close();
}
await deferreds[counter - 1];
await deferreds[counter - 1].promise;
controller.enqueue(`${counter}\n`);
counter++;
@ -795,13 +794,13 @@ Deno.test({ permissions: { net: true } }, async function httpServerWebSocket() {
await close;
})();
const def = deferred();
const def = Promise.withResolvers<void>();
const ws = new WebSocket(`ws://localhost:${listenPort}`);
ws.onmessage = (m) => assertEquals(m.data, "foo");
ws.onerror = () => fail();
ws.onclose = () => def.resolve();
ws.onopen = () => ws.send("foo");
await def;
await def.promise;
await promise;
});
@ -2287,7 +2286,7 @@ Deno.test("upgradeHttp unix", {
ignore: Deno.build.os === "windows",
}, async () => {
const filePath = tmpUnixSocketPath();
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
async function client() {
const unixConn = await Deno.connect({ path: filePath, transport: "unix" });
@ -2303,7 +2302,7 @@ Deno.test("upgradeHttp unix", {
),
);
unixConn.close();
promise.resolve();
resolve();
}, 500);
await promise;
}

View file

@ -6,8 +6,6 @@ import {
assertNotEquals,
assertRejects,
assertThrows,
Deferred,
deferred,
} from "./test_util.ts";
import { assertType, IsExact } from "../../../test_util/std/testing/types.ts";
@ -1404,11 +1402,11 @@ async function _typeCheckingTests() {
}
queueTest("basic listenQueue and enqueue", async (db) => {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
let dequeuedMessage: unknown = null;
const listener = db.listenQueue((msg) => {
dequeuedMessage = msg;
promise.resolve();
resolve();
});
try {
const res = await db.enqueue("test");
@ -1426,17 +1424,19 @@ for (const { name, value } of VALUE_CASES) {
queueTest(`listenQueue and enqueue ${name}`, async (db) => {
const numEnqueues = 10;
let count = 0;
const promises: Deferred<unknown>[] = [];
const deferreds: ReturnType<typeof Promise.withResolvers<unknown>>[] = [];
const listeners: Promise<void>[] = [];
listeners.push(db.listenQueue((msg: unknown) => {
promises[count++].resolve(msg);
deferreds[count++].resolve(msg);
}));
try {
for (let i = 0; i < numEnqueues; i++) {
promises.push(deferred());
deferreds.push(Promise.withResolvers<unknown>());
await db.enqueue(value);
}
const dequeuedMessages = await Promise.all(promises);
const dequeuedMessages = await Promise.all(
deferreds.map(({ promise }) => promise),
);
for (let i = 0; i < numEnqueues; i++) {
assertEquals(dequeuedMessages[i], value);
}
@ -1450,17 +1450,17 @@ for (const { name, value } of VALUE_CASES) {
}
queueTest("queue mixed types", async (db) => {
let promise: Deferred<void>;
let deferred: ReturnType<typeof Promise.withResolvers<void>>;
let dequeuedMessage: unknown = null;
const listener = db.listenQueue((msg: unknown) => {
dequeuedMessage = msg;
promise.resolve();
deferred.resolve();
});
try {
for (const item of VALUE_CASES) {
promise = deferred();
deferred = Promise.withResolvers<void>();
await db.enqueue(item.value);
await promise;
await deferred.promise;
assertEquals(dequeuedMessage, item.value);
}
} finally {
@ -1471,12 +1471,12 @@ queueTest("queue mixed types", async (db) => {
queueTest("queue delay", async (db) => {
let dequeueTime: number | undefined;
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
let dequeuedMessage: unknown = null;
const listener = db.listenQueue((msg) => {
dequeueTime = Date.now();
dequeuedMessage = msg;
promise.resolve();
resolve();
});
try {
const enqueueTime = Date.now();
@ -1493,12 +1493,12 @@ queueTest("queue delay", async (db) => {
queueTest("queue delay with atomic", async (db) => {
let dequeueTime: number | undefined;
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
let dequeuedMessage: unknown = null;
const listener = db.listenQueue((msg) => {
dequeueTime = Date.now();
dequeuedMessage = msg;
promise.resolve();
resolve();
});
try {
const enqueueTime = Date.now();
@ -1520,14 +1520,14 @@ queueTest("queue delay with atomic", async (db) => {
queueTest("queue delay and now", async (db) => {
let count = 0;
let dequeueTime: number | undefined;
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
let dequeuedMessage: unknown = null;
const listener = db.listenQueue((msg) => {
count += 1;
if (count == 2) {
dequeueTime = Date.now();
dequeuedMessage = msg;
promise.resolve();
resolve();
}
});
try {
@ -1564,12 +1564,12 @@ dbTest("queue large delay", async (db) => {
});
queueTest("listenQueue with async callback", async (db) => {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
let dequeuedMessage: unknown = null;
const listener = db.listenQueue(async (msg) => {
dequeuedMessage = msg;
await sleep(100);
promise.resolve();
resolve();
});
try {
await db.enqueue("test");
@ -1603,20 +1603,20 @@ queueTest("queue retries", async (db) => {
queueTest("multiple listenQueues", async (db) => {
const numListens = 10;
let count = 0;
const promises: Deferred<void>[] = [];
const deferreds: ReturnType<typeof Promise.withResolvers<void>>[] = [];
const dequeuedMessages: unknown[] = [];
const listeners: Promise<void>[] = [];
for (let i = 0; i < numListens; i++) {
listeners.push(db.listenQueue((msg) => {
dequeuedMessages.push(msg);
promises[count++].resolve();
deferreds[count++].resolve();
}));
}
try {
for (let i = 0; i < numListens; i++) {
promises.push(deferred());
deferreds.push(Promise.withResolvers<void>());
await db.enqueue("msg_" + i);
await promises[i];
await deferreds[i].promise;
const msg = dequeuedMessages[i];
assertEquals("msg_" + i, msg);
}
@ -1629,11 +1629,11 @@ queueTest("multiple listenQueues", async (db) => {
});
queueTest("enqueue with atomic", async (db) => {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
let dequeuedMessage: unknown = null;
const listener = db.listenQueue((msg) => {
dequeuedMessage = msg;
promise.resolve();
resolve();
});
try {
@ -1661,7 +1661,7 @@ queueTest("enqueue with atomic", async (db) => {
});
queueTest("enqueue with atomic nonce", async (db) => {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
let dequeuedMessage: unknown = null;
const nonce = crypto.randomUUID();
@ -1672,7 +1672,7 @@ queueTest("enqueue with atomic nonce", async (db) => {
const nonceValue = await db.get(["nonces", nonce]);
if (nonceValue.versionstamp === null) {
dequeuedMessage = message.msg;
promise.resolve();
resolve();
return;
}
@ -1720,13 +1720,13 @@ Deno.test({
let db: Deno.Kv = await Deno.openKv(filename);
let count = 0;
let promise = deferred();
let deferred = Promise.withResolvers<void>();
// Register long-running handler.
let listener = db.listenQueue(async (_msg) => {
count += 1;
if (count == 3) {
promise.resolve();
deferred.resolve();
}
await new Promise(() => {});
});
@ -1735,7 +1735,7 @@ Deno.test({
await db.enqueue("msg0");
await db.enqueue("msg1");
await db.enqueue("msg2");
await promise;
await deferred.promise;
// Close the database and wait for the listener to finish.
db.close();
@ -1751,18 +1751,18 @@ Deno.test({
db = await Deno.openKv(filename);
count = 0;
promise = deferred();
deferred = Promise.withResolvers<void>();
// Register a handler that will complete quickly.
listener = db.listenQueue((_msg) => {
count += 1;
if (count == 3) {
promise.resolve();
deferred.resolve();
}
});
// Wait for the handlers to finish.
await promise;
await deferred.promise;
assertEquals(3, count);
db.close();
await listener;
@ -1789,7 +1789,7 @@ Deno.test({
let db: Deno.Kv = await Deno.openKv(filename);
let count = 0;
let promise = deferred();
let deferred = Promise.withResolvers<void>();
// Register long-running handler.
let listener = db.listenQueue((_msg) => {});
@ -1807,18 +1807,18 @@ Deno.test({
db = await Deno.openKv(filename);
count = 0;
promise = deferred();
deferred = Promise.withResolvers<void>();
// Register a handler that will complete quickly.
listener = db.listenQueue((_msg) => {
count += 1;
if (count == 3) {
promise.resolve();
deferred.resolve();
}
});
// Wait for the handlers to finish.
await promise;
await deferred.promise;
assertEquals(3, count);
db.close();
await listener;
@ -1839,11 +1839,11 @@ Deno.test({
try {
const db0 = await Deno.openKv(filename);
const db1 = await Deno.openKv(filename);
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
let dequeuedMessage: unknown = null;
const listener = db0.listenQueue((msg) => {
dequeuedMessage = msg;
promise.resolve();
resolve();
});
try {
const res = await db1.enqueue("test");

File diff suppressed because it is too large Load diff

View file

@ -20,8 +20,6 @@ export {
unimplemented,
unreachable,
} from "../../../test_util/std/testing/asserts.ts";
export { deferred } from "../../../test_util/std/async/deferred.ts";
export type { Deferred } from "../../../test_util/std/async/deferred.ts";
export { delay } from "../../../test_util/std/async/delay.ts";
export { readLines } from "../../../test_util/std/io/read_lines.ts";
export { parse as parseArgs } from "../../../test_util/std/flags/mod.ts";

View file

@ -6,8 +6,6 @@ import {
assertRejects,
assertStrictEquals,
assertThrows,
Deferred,
deferred,
} from "./test_util.ts";
import { BufReader, BufWriter } from "../../../test_util/std/io/mod.ts";
import { readAll } from "../../../test_util/std/streams/read_all.ts";
@ -178,7 +176,7 @@ Deno.test(
Deno.test(
{ permissions: { read: true, net: true } },
async function dialAndListenTLS() {
const resolvable = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
const hostname = "localhost";
const port = 3500;
@ -201,7 +199,7 @@ Deno.test(
// TODO(bartlomieju): this might be a bug
setTimeout(() => {
conn.close();
resolvable.resolve();
resolve();
}, 0);
},
);
@ -231,13 +229,13 @@ Deno.test(
assertEquals(decoder.decode(bodyBuf), "Hello World\n");
conn.close();
listener.close();
await resolvable;
await promise;
},
);
Deno.test(
{ permissions: { read: false, net: true } },
async function listenTlsWithCertAndKey() {
const resolvable = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
const hostname = "localhost";
const port = 3500;
@ -254,7 +252,7 @@ Deno.test(
await conn.write(response);
setTimeout(() => {
conn.close();
resolvable.resolve();
resolve();
}, 0);
},
);
@ -284,7 +282,7 @@ Deno.test(
assertEquals(decoder.decode(bodyBuf), "Hello World\n");
conn.close();
listener.close();
await resolvable;
await promise;
},
);
@ -770,20 +768,20 @@ async function tlsWithTcpFailureTestImpl(
tcpConn2: tcpClientConn,
};
const tcpForwardingInterruptPromise1 = deferred<void>();
const tcpForwardingInterruptDeferred1 = Promise.withResolvers<void>();
const tcpForwardingPromise1 = forwardBytes(
tcpConn2,
tcpConn1,
cipherByteCount,
tcpForwardingInterruptPromise1,
tcpForwardingInterruptDeferred1,
);
const tcpForwardingInterruptPromise2 = deferred<void>();
const tcpForwardingInterruptDeferred2 = Promise.withResolvers<void>();
const tcpForwardingPromise2 = forwardBytes(
tcpConn1,
tcpConn2,
Infinity,
tcpForwardingInterruptPromise2,
tcpForwardingInterruptDeferred2,
);
switch (phase) {
@ -836,7 +834,7 @@ async function tlsWithTcpFailureTestImpl(
}
await tlsTrafficPromise1;
tcpForwardingInterruptPromise2.resolve();
tcpForwardingInterruptDeferred2.resolve();
await tcpForwardingPromise2;
await tcpConn2.closeWrite();
await tlsTrafficPromise2;
@ -852,8 +850,8 @@ async function tlsWithTcpFailureTestImpl(
receiveBytes(tlsConn2, 0x99, 99999),
]);
tcpForwardingInterruptPromise1.resolve();
await tcpForwardingPromise1;
tcpForwardingInterruptDeferred1.resolve();
await tcpForwardingInterruptDeferred1.promise;
switch (failureMode) {
case "corruption":
@ -862,7 +860,7 @@ async function tlsWithTcpFailureTestImpl(
() => receiveEof(tlsConn1),
Deno.errors.InvalidData,
);
tcpForwardingInterruptPromise2.resolve();
tcpForwardingInterruptDeferred2.resolve();
break;
case "shutdown":
await Promise.all([
@ -934,12 +932,15 @@ async function tlsWithTcpFailureTestImpl(
source: Deno.Conn,
sink: Deno.Conn,
count: number,
interruptPromise: Deferred<void>,
interruptPromise: ReturnType<typeof Promise.withResolvers<void>>,
) {
let buf = new Uint8Array(1 << 12 /* 4 kB */);
while (count > 0) {
buf = buf.subarray(0, Math.min(buf.length, count));
const nread = await Promise.race([source.read(buf), interruptPromise]);
const nread = await Promise.race([
source.read(buf),
interruptPromise.promise,
]);
if (nread == null) break; // Either EOF or interrupted.
const nwritten = await sink.write(buf.subarray(0, nread));
assertStrictEquals(nread, nwritten);
@ -1405,7 +1406,7 @@ Deno.test(
Deno.test(
{ permissions: { net: true } },
async function listenTlsWithReuseAddr() {
const resolvable1 = deferred();
const deferred1 = Promise.withResolvers<void>();
const hostname = "localhost";
const port = 3500;
@ -1413,25 +1414,25 @@ Deno.test(
listener1.accept().then((conn) => {
conn.close();
resolvable1.resolve();
deferred1.resolve();
});
const conn1 = await Deno.connectTls({ hostname, port, caCerts });
conn1.close();
await resolvable1;
await deferred1.promise;
listener1.close();
const resolvable2 = deferred();
const deferred2 = Promise.withResolvers<void>();
const listener2 = Deno.listenTls({ hostname, port, cert, key });
listener2.accept().then((conn) => {
conn.close();
resolvable2.resolve();
deferred2.resolve();
});
const conn2 = await Deno.connectTls({ hostname, port, caCerts });
conn2.close();
await resolvable2;
await deferred2.promise;
listener2.close();
},
);

View file

@ -1,11 +1,5 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
import {
assert,
assertEquals,
assertThrows,
deferred,
fail,
} from "./test_util.ts";
import { assert, assertEquals, assertThrows, fail } from "./test_util.ts";
const servePort = 4248;
const serveUrl = `ws://localhost:${servePort}/`;
@ -18,23 +12,23 @@ Deno.test({ permissions: "none" }, function websocketPermissionless() {
});
Deno.test(async function websocketConstructorTakeURLObjectAsParameter() {
const promise = deferred();
const { promise, resolve, reject } = Promise.withResolvers<void>();
const ws = new WebSocket(new URL("ws://localhost:4242/"));
assertEquals(ws.url, "ws://localhost:4242/");
ws.onerror = (e) => promise.reject(e);
ws.onerror = (e) => reject(e);
ws.onopen = () => ws.close();
ws.onclose = () => {
promise.resolve();
resolve();
};
await promise;
});
Deno.test(async function websocketH2SendSmallPacket() {
const promise = deferred();
const { promise, resolve, reject } = Promise.withResolvers<void>();
const ws = new WebSocket(new URL("wss://localhost:4249/"));
assertEquals(ws.url, "wss://localhost:4249/");
let messageCount = 0;
ws.onerror = (e) => promise.reject(e);
ws.onerror = (e) => reject(e);
ws.onopen = () => {
ws.send("a".repeat(16));
ws.send("a".repeat(16));
@ -46,17 +40,17 @@ Deno.test(async function websocketH2SendSmallPacket() {
}
};
ws.onclose = () => {
promise.resolve();
resolve();
};
await promise;
});
Deno.test(async function websocketH2SendLargePacket() {
const promise = deferred();
const { promise, resolve, reject } = Promise.withResolvers<void>();
const ws = new WebSocket(new URL("wss://localhost:4249/"));
assertEquals(ws.url, "wss://localhost:4249/");
let messageCount = 0;
ws.onerror = (e) => promise.reject(e);
ws.onerror = (e) => reject(e);
ws.onopen = () => {
ws.send("a".repeat(65000));
ws.send("a".repeat(65000));
@ -68,16 +62,16 @@ Deno.test(async function websocketH2SendLargePacket() {
}
};
ws.onclose = () => {
promise.resolve();
resolve();
};
await promise;
});
Deno.test(async function websocketSendLargePacket() {
const promise = deferred();
const { promise, resolve, reject } = Promise.withResolvers<void>();
const ws = new WebSocket(new URL("wss://localhost:4243/"));
assertEquals(ws.url, "wss://localhost:4243/");
ws.onerror = (e) => promise.reject(e);
ws.onerror = (e) => reject(e);
ws.onopen = () => {
ws.send("a".repeat(65000));
};
@ -85,17 +79,17 @@ Deno.test(async function websocketSendLargePacket() {
ws.close();
};
ws.onclose = () => {
promise.resolve();
resolve();
};
await promise;
});
Deno.test(async function websocketSendLargeBinaryPacket() {
const promise = deferred();
const { promise, resolve, reject } = Promise.withResolvers<void>();
const ws = new WebSocket(new URL("wss://localhost:4243/"));
ws.binaryType = "arraybuffer";
assertEquals(ws.url, "wss://localhost:4243/");
ws.onerror = (e) => promise.reject(e);
ws.onerror = (e) => reject(e);
ws.onopen = () => {
ws.send(new Uint8Array(65000));
};
@ -104,17 +98,17 @@ Deno.test(async function websocketSendLargeBinaryPacket() {
ws.close();
};
ws.onclose = () => {
promise.resolve();
resolve();
};
await promise;
});
Deno.test(async function websocketSendLargeBlobPacket() {
const promise = deferred();
const { promise, resolve, reject } = Promise.withResolvers<void>();
const ws = new WebSocket(new URL("wss://localhost:4243/"));
ws.binaryType = "arraybuffer";
assertEquals(ws.url, "wss://localhost:4243/");
ws.onerror = (e) => promise.reject(e);
ws.onerror = (e) => reject(e);
ws.onopen = () => {
ws.send(new Blob(["a".repeat(65000)]));
};
@ -123,7 +117,7 @@ Deno.test(async function websocketSendLargeBlobPacket() {
ws.close();
};
ws.onclose = () => {
promise.resolve();
resolve();
};
await promise;
});
@ -131,15 +125,15 @@ Deno.test(async function websocketSendLargeBlobPacket() {
// https://github.com/denoland/deno/pull/17762
// https://github.com/denoland/deno/issues/17761
Deno.test(async function websocketPingPong() {
const promise = deferred();
const { promise, resolve, reject } = Promise.withResolvers<void>();
const ws = new WebSocket("ws://localhost:4245/");
assertEquals(ws.url, "ws://localhost:4245/");
ws.onerror = (e) => promise.reject(e);
ws.onerror = (e) => reject(e);
ws.onmessage = (e) => {
ws.send(e.data);
};
ws.onclose = () => {
promise.resolve();
resolve();
};
await promise;
ws.close();
@ -147,7 +141,7 @@ Deno.test(async function websocketPingPong() {
// TODO(mmastrac): This requires us to ignore bad certs
// Deno.test(async function websocketSecureConnect() {
// const promise = deferred();
// const { promise, resolve } = Promise.withResolvers<void>();
// const ws = new WebSocket("wss://localhost:4243/");
// assertEquals(ws.url, "wss://localhost:4243/");
// ws.onerror = (error) => {
@ -156,7 +150,7 @@ Deno.test(async function websocketPingPong() {
// };
// ws.onopen = () => ws.close();
// ws.onclose = () => {
// promise.resolve();
// resolve();
// };
// await promise;
// });
@ -166,7 +160,7 @@ Deno.test(
{ sanitizeOps: false, sanitizeResources: false },
async function websocketWriteLock() {
const ac = new AbortController();
const listeningPromise = deferred();
const listeningDeferred = Promise.withResolvers<void>();
const server = Deno.serve({
handler: (req) => {
@ -181,13 +175,13 @@ Deno.test(
return response;
},
signal: ac.signal,
onListen: () => listeningPromise.resolve(),
onListen: () => listeningDeferred.resolve(),
hostname: "localhost",
port: servePort,
});
await listeningPromise;
const promise = deferred();
await listeningDeferred.promise;
const deferred = Promise.withResolvers<void>();
const ws = new WebSocket(serveUrl);
assertEquals(ws.url, serveUrl);
ws.onerror = () => fail();
@ -196,13 +190,13 @@ Deno.test(
setTimeout(() => {
ws.send(e.data);
}, 1000);
promise.resolve();
deferred.resolve();
};
ws.onclose = () => {
promise.resolve();
deferred.resolve();
};
await Promise.all([promise, server.finished]);
await Promise.all([deferred.promise, server.finished]);
ws.close();
},
);
@ -212,10 +206,10 @@ Deno.test({
sanitizeOps: false,
sanitizeResources: false,
}, async function websocketDoubleClose() {
const promise = deferred();
const deferred = Promise.withResolvers<void>();
const ac = new AbortController();
const listeningPromise = deferred();
const listeningDeferred = Promise.withResolvers<void>();
const server = Deno.serve({
handler: (req) => {
@ -233,12 +227,12 @@ Deno.test({
return response;
},
signal: ac.signal,
onListen: () => listeningPromise.resolve(),
onListen: () => listeningDeferred.resolve(),
hostname: "localhost",
port: servePort,
});
await listeningPromise;
await listeningDeferred.promise;
const ws = new WebSocket(serveUrl);
assertEquals(ws.url, serveUrl);
@ -247,9 +241,9 @@ Deno.test({
if (m.data == "Hello") ws.send("bye");
};
ws.onclose = () => {
promise.resolve();
deferred.resolve();
};
await Promise.all([promise, server.finished]);
await Promise.all([deferred.promise, server.finished]);
});
// https://github.com/denoland/deno/issues/19483
@ -257,10 +251,10 @@ Deno.test({
sanitizeOps: false,
sanitizeResources: false,
}, async function websocketCloseFlushes() {
const promise = deferred();
const deferred = Promise.withResolvers<void>();
const ac = new AbortController();
const listeningPromise = deferred();
const listeningDeferred = Promise.withResolvers<void>();
const server = Deno.serve({
handler: (req) => {
@ -275,12 +269,12 @@ Deno.test({
return response;
},
signal: ac.signal,
onListen: () => listeningPromise.resolve(),
onListen: () => listeningDeferred.resolve(),
hostname: "localhost",
port: servePort,
});
await listeningPromise;
await listeningDeferred.promise;
const ws = new WebSocket(serveUrl);
assertEquals(ws.url, serveUrl);
@ -295,9 +289,9 @@ Deno.test({
}
};
ws.onclose = () => {
promise.resolve();
deferred.resolve();
};
await Promise.all([promise, server.finished]);
await Promise.all([deferred.promise, server.finished]);
assert(seenBye);
});

View file

@ -10,7 +10,6 @@ import { open, openSync } from "node:fs";
import { Buffer } from "node:buffer";
import * as path from "../../../../test_util/std/path/mod.ts";
import { closeSync } from "node:fs";
import { deferred } from "../../../../test_util/std/async/deferred.ts";
async function readTest(
testData: string,
@ -132,7 +131,7 @@ Deno.test({
Deno.test({
name: "[std/node/fs] Read fs.read(fd, options, cb) signature",
async fn() {
const promise = deferred();
const { promise, reject, resolve } = Promise.withResolvers<void>();
const file = Deno.makeTempFileSync();
Deno.writeTextFileSync(file, "hi there");
const fd = openSync(file, "r+");
@ -154,10 +153,10 @@ Deno.test({
Buffer.from([104, 105, 32, 116, 104, 101, 114, 101, 0, 0, 0]),
);
} catch (e) {
promise.reject(e);
reject(e);
return;
}
promise.resolve();
resolve();
},
);
closeSync(fd);
@ -168,7 +167,7 @@ Deno.test({
Deno.test({
name: "[std/node/fs] Read fs.read(fd, cb) signature",
async fn() {
const promise = deferred();
const { promise, resolve, reject } = Promise.withResolvers<void>();
const file = Deno.makeTempFileSync();
Deno.writeTextFileSync(file, "hi deno");
const fd = openSync(file, "r+");
@ -178,10 +177,10 @@ Deno.test({
assertStrictEquals(bytesRead, 7);
assertStrictEquals(data?.byteLength, 16384);
} catch (e) {
promise.reject(e);
reject(e);
return;
}
promise.resolve();
resolve();
});
closeSync(fd);
await promise;
@ -277,27 +276,27 @@ Deno.test({
await Deno.writeTextFile(file, "abc");
await t.step("without position option", async () => {
const promise = deferred<void>();
const { promise, resolve } = Promise.withResolvers<void>();
let called = false;
const fd = openSync(file, "r");
read(fd, () => {
called = true;
closeSync(fd);
promise.resolve();
resolve();
});
assertFalse(called);
await promise;
});
await t.step("with position option", async () => {
const promise = deferred<void>();
const { promise, resolve } = Promise.withResolvers<void>();
let called = false;
const buffer = Buffer.alloc(2);
const fd = openSync(file, "r");
read(fd, { position: 1, buffer, offset: 0, length: 2 }, () => {
called = true;
closeSync(fd);
promise.resolve();
resolve();
});
assertFalse(called);
await promise;

View file

@ -4,7 +4,6 @@ import {
assert,
assertEquals,
} from "../../../test_util/std/testing/asserts.ts";
import { deferred } from "../../../test_util/std/async/deferred.ts";
Deno.test(async function foo() {
const asyncLocalStorage = new AsyncLocalStorage();
@ -68,16 +67,16 @@ Deno.test(async function bar() {
Deno.test(async function nested() {
const als = new AsyncLocalStorage();
const promise = deferred();
const promise1 = deferred();
const deferred = Promise.withResolvers();
const deferred1 = Promise.withResolvers();
als.run(null, () => {
als.run({ x: 1 }, () => {
promise.resolve(als.getStore());
deferred.resolve(als.getStore());
});
promise1.resolve(als.getStore());
deferred1.resolve(als.getStore());
});
assertEquals(await promise, { x: 1 });
assertEquals(await promise1, null);
assertEquals(await deferred.promise, { x: 1 });
assertEquals(await deferred1.promise, null);
});

View file

@ -10,45 +10,46 @@ import {
assertStrictEquals,
assertStringIncludes,
} from "../../../test_util/std/testing/asserts.ts";
import { Deferred, deferred } from "../../../test_util/std/async/deferred.ts";
import * as path from "../../../test_util/std/path/mod.ts";
const { spawn, spawnSync, execFile, execFileSync, ChildProcess } = CP;
function withTimeout<T>(timeoutInMS = 10_000): Deferred<T> {
const promise = deferred<T>();
function withTimeout<T>(
timeoutInMS = 10_000,
): ReturnType<typeof Promise.withResolvers<T>> {
const deferred = Promise.withResolvers<T>();
const timer = setTimeout(() => {
promise.reject("Timeout");
deferred.reject("Timeout");
}, timeoutInMS);
promise.then(() => {
deferred.promise.then(() => {
clearTimeout(timer);
});
return promise;
return deferred;
}
// TODO(uki00a): Once Node.js's `parallel/test-child-process-spawn-error.js` works, this test case should be removed.
Deno.test("[node/child_process spawn] The 'error' event is emitted when no binary is found", async () => {
const promise = withTimeout();
const deferred = withTimeout<void>();
const childProcess = spawn("no-such-cmd");
childProcess.on("error", (_err: Error) => {
// TODO(@bartlomieju) Assert an error message.
promise.resolve();
deferred.resolve();
});
await promise;
await deferred.promise;
});
Deno.test("[node/child_process spawn] The 'exit' event is emitted with an exit code after the child process ends", async () => {
const promise = withTimeout();
const deferred = withTimeout<void>();
const childProcess = spawn(Deno.execPath(), ["--help"], {
env: { NO_COLOR: "true" },
});
try {
let exitCode = null;
childProcess.on("exit", (code: number) => {
promise.resolve();
deferred.resolve();
exitCode = code;
});
await promise;
await deferred.promise;
assertStrictEquals(exitCode, 0);
assertStrictEquals(childProcess.exitCode, exitCode);
} finally {
@ -59,16 +60,16 @@ Deno.test("[node/child_process spawn] The 'exit' event is emitted with an exit c
});
Deno.test("[node/child_process disconnect] the method exists", async () => {
const promise = withTimeout();
const deferred = withTimeout<void>();
const childProcess = spawn(Deno.execPath(), ["--help"], {
env: { NO_COLOR: "true" },
});
try {
childProcess.disconnect();
childProcess.on("exit", () => {
promise.resolve();
deferred.resolve();
});
await promise;
await deferred.promise;
} finally {
childProcess.kill();
childProcess.stdout?.destroy();
@ -79,7 +80,7 @@ Deno.test("[node/child_process disconnect] the method exists", async () => {
Deno.test({
name: "[node/child_process spawn] Verify that stdin and stdout work",
fn: async () => {
const promise = withTimeout();
const deferred = withTimeout<void>();
const childProcess = spawn(Deno.execPath(), ["fmt", "-"], {
env: { NO_COLOR: "true" },
stdio: ["pipe", "pipe"],
@ -94,9 +95,9 @@ Deno.test({
childProcess.stdin.write(" console.log('hello')", "utf-8");
childProcess.stdin.end();
childProcess.on("close", () => {
promise.resolve();
deferred.resolve();
});
await promise;
await deferred.promise;
assertStrictEquals(data, `console.log("hello");\n`);
} finally {
childProcess.kill();
@ -107,7 +108,7 @@ Deno.test({
Deno.test({
name: "[node/child_process spawn] stdin and stdout with binary data",
fn: async () => {
const promise = withTimeout();
const deferred = withTimeout<void>();
const p = path.join(
path.dirname(path.fromFileUrl(import.meta.url)),
"./testdata/binary_stdio.js",
@ -127,9 +128,9 @@ Deno.test({
childProcess.stdin.write(buffer);
childProcess.stdin.end();
childProcess.on("close", () => {
promise.resolve();
deferred.resolve();
});
await promise;
await deferred.promise;
assertEquals(new Uint8Array(data!), buffer);
} finally {
childProcess.kill();
@ -140,7 +141,7 @@ Deno.test({
async function spawnAndGetEnvValue(
inputValue: string | number | boolean,
): Promise<string> {
const promise = withTimeout<string>();
const deferred = withTimeout<string>();
const env = spawn(
`"${Deno.execPath()}" eval -p "Deno.env.toObject().BAZ"`,
{
@ -152,14 +153,14 @@ async function spawnAndGetEnvValue(
let envOutput = "";
assert(env.stdout);
env.on("error", (err: Error) => promise.reject(err));
env.on("error", (err: Error) => deferred.reject(err));
env.stdout.on("data", (data) => {
envOutput += data;
});
env.on("close", () => {
promise.resolve(envOutput.trim());
deferred.resolve(envOutput.trim());
});
return await promise;
return await deferred.promise;
} finally {
env.kill();
}
@ -191,7 +192,7 @@ Deno.test({
// TODO(uki00a): Remove this case once Node's `parallel/test-child-process-spawn-event.js` works.
Deno.test("[child_process spawn] 'spawn' event", async () => {
const timeout = withTimeout();
const timeout = withTimeout<void>();
const subprocess = spawn(Deno.execPath(), ["eval", "console.log('ok')"]);
let didSpawn = false;
@ -205,13 +206,13 @@ Deno.test("[child_process spawn] 'spawn' event", async () => {
const promises = [] as Promise<void>[];
function mustBeCalledAfterSpawn() {
const promise = deferred<void>();
promises.push(promise);
const deferred = Promise.withResolvers<void>();
promises.push(deferred.promise);
return () => {
if (didSpawn) {
promise.resolve();
deferred.resolve();
} else {
promise.reject(
deferred.reject(
new Error("function should be called after the 'spawn' event"),
);
}
@ -229,7 +230,7 @@ Deno.test("[child_process spawn] 'spawn' event", async () => {
subprocess.on("close", mustBeCalledAfterSpawn());
try {
await Promise.race([Promise.all(promises), timeout]);
await Promise.race([Promise.all(promises), timeout.promise]);
timeout.resolve();
} finally {
subprocess.kill();
@ -238,12 +239,12 @@ Deno.test("[child_process spawn] 'spawn' event", async () => {
// TODO(uki00a): Remove this case once Node's `parallel/test-child-process-spawn-shell.js` works.
Deno.test("[child_process spawn] Verify that a shell is executed", async () => {
const promise = withTimeout();
const deferred = withTimeout<void>();
const doesNotExist = spawn("does-not-exist", { shell: true });
try {
assertNotStrictEquals(doesNotExist.spawnfile, "does-not-exist");
doesNotExist.on("error", () => {
promise.reject("The 'error' event must not be emitted.");
deferred.reject("The 'error' event must not be emitted.");
});
doesNotExist.on("exit", (code: number, signal: null) => {
assertStrictEquals(signal, null);
@ -254,9 +255,9 @@ Deno.test("[child_process spawn] Verify that a shell is executed", async () => {
assertStrictEquals(code, 127); // Exit code of /bin/sh });
}
promise.resolve();
deferred.resolve();
});
await promise;
await deferred.promise;
} finally {
doesNotExist.kill();
doesNotExist.stdout?.destroy();
@ -269,7 +270,7 @@ Deno.test({
ignore: Deno.build.os === "windows",
name: "[node/child_process spawn] Verify that passing arguments works",
async fn() {
const promise = withTimeout();
const deferred = withTimeout<void>();
const echo = spawn("echo", ["foo"], {
shell: true,
});
@ -286,9 +287,9 @@ Deno.test({
});
echo.on("close", () => {
assertStrictEquals(echoOutput.trim(), "foo");
promise.resolve();
deferred.resolve();
});
await promise;
await deferred.promise;
} finally {
echo.kill();
}
@ -300,7 +301,7 @@ Deno.test({
ignore: Deno.build.os === "windows",
name: "[node/child_process spawn] Verity that shell features can be used",
async fn() {
const promise = withTimeout();
const deferred = withTimeout<void>();
const cmd = "echo bar | cat";
const command = spawn(cmd, {
shell: true,
@ -315,10 +316,10 @@ Deno.test({
command.on("close", () => {
assertStrictEquals(commandOutput.trim(), "bar");
promise.resolve();
deferred.resolve();
});
await promise;
await deferred.promise;
} finally {
command.kill();
}
@ -331,7 +332,7 @@ Deno.test({
name:
"[node/child_process spawn] Verity that environment is properly inherited",
async fn() {
const promise = withTimeout();
const deferred = withTimeout<void>();
const env = spawn(
`"${Deno.execPath()}" eval -p "Deno.env.toObject().BAZ"`,
{
@ -343,15 +344,15 @@ Deno.test({
let envOutput = "";
assert(env.stdout);
env.on("error", (err: Error) => promise.reject(err));
env.on("error", (err: Error) => deferred.reject(err));
env.stdout.on("data", (data) => {
envOutput += data;
});
env.on("close", () => {
assertStrictEquals(envOutput.trim(), "buzz");
promise.resolve();
deferred.resolve();
});
await promise;
await deferred.promise;
} finally {
env.kill();
}
@ -496,16 +497,16 @@ Deno.test({
"./testdata/infinite_loop.js",
);
const childProcess = spawn(Deno.execPath(), ["run", script]);
const p = withTimeout();
const pStdout = withTimeout();
const pStderr = withTimeout();
const p = withTimeout<void>();
const pStdout = withTimeout<void>();
const pStderr = withTimeout<void>();
childProcess.on("exit", () => p.resolve());
childProcess.stdout.on("close", () => pStdout.resolve());
childProcess.stderr.on("close", () => pStderr.resolve());
childProcess.kill("SIGKILL");
await p;
await pStdout;
await pStderr;
await p.promise;
await pStdout.promise;
await pStderr.promise;
assert(childProcess.killed);
assertEquals(childProcess.signalCode, "SIGKILL");
assertExists(childProcess.exitCode);
@ -527,9 +528,9 @@ Deno.test({
"--unstable",
script,
]);
const p = deferred();
childProcess.on("exit", () => p.resolve());
await p;
const deferred = Promise.withResolvers<void>();
childProcess.on("exit", () => deferred.resolve());
await deferred.promise;
},
});
@ -547,14 +548,14 @@ Deno.test({
"foo",
"index.js",
);
const p = deferred();
const p = Promise.withResolvers<void>();
const cp = CP.fork(script, [], { cwd: testdataDir, stdio: "pipe" });
let output = "";
cp.on("close", () => p.resolve());
cp.stdout?.on("data", (data) => {
output += data;
});
await p;
await p.promise;
assertEquals(output, "foo\ntrue\ntrue\ntrue\n");
},
});
@ -567,7 +568,7 @@ Deno.test(
"[node/child_process spawn] supports windowsVerbatimArguments option",
{ ignore: Deno.build.os !== "windows" },
async () => {
const cmdFinished = deferred();
const cmdFinished = Promise.withResolvers<void>();
let output = "";
const cp = spawn("cmd", ["/d", "/s", "/c", '"deno ^"--version^""'], {
stdio: "pipe",
@ -577,7 +578,7 @@ Deno.test(
cp.stdout?.on("data", (data) => {
output += data;
});
await cmdFinished;
await cmdFinished.promise;
assertStringIncludes(output, "deno");
assertStringIncludes(output, "v8");
assertStringIncludes(output, "typescript");
@ -587,7 +588,7 @@ Deno.test(
Deno.test(
"[node/child_process spawn] supports stdio array option",
async () => {
const cmdFinished = deferred();
const cmdFinished = Promise.withResolvers<void>();
let output = "";
const script = path.join(
path.dirname(path.fromFileUrl(import.meta.url)),
@ -599,7 +600,7 @@ Deno.test(
output += data;
});
cp.on("close", () => cmdFinished.resolve());
await cmdFinished;
await cmdFinished.promise;
assertStringIncludes(output, "foo");
assertStringIncludes(output, "close");
@ -609,7 +610,7 @@ Deno.test(
Deno.test(
"[node/child_process spawn] supports stdio [0, 1, 2] option",
async () => {
const cmdFinished = deferred();
const cmdFinished = Promise.withResolvers<void>();
let output = "";
const script = path.join(
path.dirname(path.fromFileUrl(import.meta.url)),
@ -621,7 +622,7 @@ Deno.test(
output += data;
});
cp.on("close", () => cmdFinished.resolve());
await cmdFinished;
await cmdFinished.promise;
assertStringIncludes(output, "foo");
assertStringIncludes(output, "close");
@ -638,16 +639,16 @@ Deno.test({
// Spawn an infinite cat
const cp = spawn("cat", ["-"]);
const p = withTimeout();
const pStdout = withTimeout();
const pStderr = withTimeout();
const p = withTimeout<void>();
const pStdout = withTimeout<void>();
const pStderr = withTimeout<void>();
cp.on("exit", () => p.resolve());
cp.stdout.on("close", () => pStdout.resolve());
cp.stderr.on("close", () => pStderr.resolve());
cp.kill("SIGIOT");
await p;
await pStdout;
await pStderr;
await p.promise;
await pStdout.promise;
await pStderr.promise;
assert(cp.killed);
assertEquals(cp.signalCode, "SIGIOT");
},
@ -655,7 +656,7 @@ Deno.test({
// Regression test for https://github.com/denoland/deno/issues/20373
Deno.test(async function undefinedValueInEnvVar() {
const promise = withTimeout<string>();
const deferred = withTimeout<string>();
const env = spawn(
`"${Deno.execPath()}" eval -p "Deno.env.toObject().BAZ"`,
{
@ -673,18 +674,18 @@ Deno.test(async function undefinedValueInEnvVar() {
let envOutput = "";
assert(env.stdout);
env.on("error", (err: Error) => promise.reject(err));
env.on("error", (err: Error) => deferred.reject(err));
env.stdout.on("data", (data) => {
envOutput += data;
});
env.on("close", () => {
promise.resolve(envOutput.trim());
deferred.resolve(envOutput.trim());
});
await promise;
await deferred.promise;
} finally {
env.kill();
}
const value = await promise;
const value = await deferred.promise;
assertEquals(value, "BAZ");
});

View file

@ -1,12 +1,11 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
import { deferred } from "../../../test_util/std/async/deferred.ts";
import { EventEmitter } from "node:events";
EventEmitter.captureRejections = true;
Deno.test("regression #20441", async () => {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
const ee = new EventEmitter();
@ -20,7 +19,7 @@ Deno.test("regression #20441", async () => {
});
ee.on("error", function (_) {
promise.resolve();
resolve();
});
ee.emit("foo");

View file

@ -2,7 +2,6 @@
import * as http2 from "node:http2";
import * as net from "node:net";
import { deferred } from "../../../test_util/std/async/deferred.ts";
import { assertEquals } from "../../../test_util/std/testing/asserts.ts";
for (const url of ["http://127.0.0.1:4246", "https://127.0.0.1:4247"]) {
@ -41,17 +40,17 @@ for (const url of ["http://127.0.0.1:4246", "https://127.0.0.1:4247"]) {
});
req.end();
const endPromise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
setTimeout(() => {
try {
client.close();
} catch (_) {
// pass
}
endPromise.resolve();
resolve();
}, 2000);
await endPromise;
await promise;
assertEquals(receivedHeaders, { ":status": 200 });
assertEquals(receivedData, "hello world\n");
@ -67,14 +66,14 @@ Deno.test(`[node/http2 client createConnection]`, {
ignore: Deno.build.os === "windows",
}, async () => {
const url = "http://127.0.0.1:4246";
const createConnPromise = deferred();
const createConnDeferred = Promise.withResolvers<void>();
// Create a server to respond to the HTTP2 requests
const client = http2.connect(url, {
createConnection() {
const socket = net.connect({ host: "127.0.0.1", port: 4246 });
socket.on("connect", () => {
createConnPromise.resolve();
createConnDeferred.resolve();
});
return socket;
@ -94,7 +93,7 @@ Deno.test(`[node/http2 client createConnection]`, {
});
req.end();
const endPromise = deferred();
const endPromise = Promise.withResolvers<void>();
setTimeout(() => {
try {
client.close();
@ -104,8 +103,8 @@ Deno.test(`[node/http2 client createConnection]`, {
endPromise.resolve();
}, 2000);
await createConnPromise;
await endPromise;
await createConnDeferred.promise;
await endPromise.promise;
assertEquals(receivedData, "hello world\n");
});
@ -127,11 +126,9 @@ Deno.test("[node/http2 server]", { sanitizeOps: false }, async () => {
const stream = await new Promise<http2.ServerHttp2Stream>((resolve) =>
session.on("stream", resolve)
);
const _headers = await new Promise((resolve) =>
stream.on("headers", resolve)
);
const _data = await new Promise((resolve) => stream.on("data", resolve));
const _end = await new Promise((resolve) => stream.on("end", resolve));
await new Promise((resolve) => stream.on("headers", resolve));
await new Promise((resolve) => stream.on("data", resolve));
await new Promise((resolve) => stream.on("end", resolve));
stream.respond();
stream.end();
const resp = await responsePromise;

View file

@ -9,7 +9,6 @@ import {
fail,
} from "../../../test_util/std/testing/asserts.ts";
import { assertSpyCalls, spy } from "../../../test_util/std/testing/mock.ts";
import { deferred } from "../../../test_util/std/async/deferred.ts";
import { gzip } from "node:zlib";
import { Buffer } from "node:buffer";
@ -28,42 +27,42 @@ Deno.test("[node/http listen]", async () => {
}
{
const promise = deferred<void>();
const { promise, resolve } = Promise.withResolvers<void>();
const server = http.createServer();
server.listen(() => {
server.close();
});
server.on("close", () => {
promise.resolve();
resolve();
});
await promise;
}
{
const promise = deferred<void>();
const { promise, resolve } = Promise.withResolvers<void>();
const server = http.createServer();
server.listen().on("listening", () => {
server.close();
});
server.on("close", () => {
promise.resolve();
resolve();
});
await promise;
}
for (const port of [0, -0, 0.0, "0", null, undefined]) {
const promise = deferred<void>();
const { promise, resolve } = Promise.withResolvers<void>();
const server = http.createServer();
server.listen(port, () => {
server.close();
});
server.on("close", () => {
promise.resolve();
resolve();
});
await promise;
@ -72,43 +71,43 @@ Deno.test("[node/http listen]", async () => {
Deno.test("[node/http close]", async () => {
{
const promise1 = deferred<void>();
const promise2 = deferred<void>();
const deferred1 = Promise.withResolvers<void>();
const deferred2 = Promise.withResolvers<void>();
// Node quirk: callback gets exception object, event listener does not.
// deno-lint-ignore no-explicit-any
const server = http.createServer().close((err: any) => {
assertEquals(err.code, "ERR_SERVER_NOT_RUNNING");
promise1.resolve();
deferred1.resolve();
});
// deno-lint-ignore no-explicit-any
server.on("close", (err: any) => {
assertEquals(err, undefined);
promise2.resolve();
deferred2.resolve();
});
server.on("listening", () => {
throw Error("unreachable");
});
await promise1;
await promise2;
await deferred1.promise;
await deferred2.promise;
}
{
const promise1 = deferred<void>();
const promise2 = deferred<void>();
const deferred1 = Promise.withResolvers<void>();
const deferred2 = Promise.withResolvers<void>();
const server = http.createServer().listen().close((err) => {
assertEquals(err, undefined);
promise1.resolve();
deferred1.resolve();
});
// deno-lint-ignore no-explicit-any
server.on("close", (err: any) => {
assertEquals(err, undefined);
promise2.resolve();
deferred2.resolve();
});
server.on("listening", () => {
throw Error("unreachable");
});
await promise1;
await promise2;
await deferred1.promise;
await deferred2.promise;
}
});
@ -117,7 +116,7 @@ Deno.test("[node/http] chunked response", async () => {
const body of [undefined, "", "ok"]
) {
const expected = body ?? "";
const promise = deferred<void>();
const { promise, resolve } = Promise.withResolvers<void>();
const server = http.createServer((_req, res) => {
res.writeHead(200, { "transfer-encoding": "chunked" });
@ -134,7 +133,7 @@ Deno.test("[node/http] chunked response", async () => {
const actual = await res.text();
assertEquals(actual, expected);
server.close(() => promise.resolve());
server.close(() => resolve());
});
await promise;
@ -143,7 +142,7 @@ Deno.test("[node/http] chunked response", async () => {
// Test empty chunks: https://github.com/denoland/deno/issues/17194
Deno.test("[node/http] empty chunk in the middle of response", async () => {
const promise = deferred<void>();
const { promise, resolve } = Promise.withResolvers<void>();
const server = http.createServer((_req, res) => {
res.write("a");
@ -159,7 +158,7 @@ Deno.test("[node/http] empty chunk in the middle of response", async () => {
);
const actual = await res.text();
assertEquals(actual, "ab");
server.close(() => promise.resolve());
server.close(() => resolve());
});
await promise;
@ -167,7 +166,7 @@ Deno.test("[node/http] empty chunk in the middle of response", async () => {
Deno.test("[node/http] server can respond with 101, 204, 205, 304 status", async () => {
for (const status of [101, 204, 205, 304]) {
const promise = deferred<void>();
const { promise, resolve } = Promise.withResolvers<void>();
const server = http.createServer((_req, res) => {
res.statusCode = status;
res.end("");
@ -179,15 +178,15 @@ Deno.test("[node/http] server can respond with 101, 204, 205, 304 status", async
);
await res.arrayBuffer();
assertEquals(res.status, status);
server.close(() => promise.resolve());
server.close(() => resolve());
});
await promise;
}
});
Deno.test("[node/http] request default protocol", async () => {
const promise = deferred<void>();
const promise2 = deferred<void>();
const deferred1 = Promise.withResolvers<void>();
const deferred2 = Promise.withResolvers<void>();
const server = http.createServer((_, res) => {
res.end("ok");
});
@ -210,22 +209,22 @@ Deno.test("[node/http] request default protocol", async () => {
});
clientRes = res;
assertEquals(res.statusCode, 200);
promise2.resolve();
deferred2.resolve();
},
);
clientReq.end();
});
server.on("close", () => {
promise.resolve();
deferred1.resolve();
});
await promise;
await promise2;
await deferred1.promise;
await deferred2.promise;
assert(clientReq.socket instanceof EventEmitter);
assertEquals(clientRes!.complete, true);
});
Deno.test("[node/http] request with headers", async () => {
const promise = deferred<void>();
const { promise, resolve } = Promise.withResolvers<void>();
const server = http.createServer((req, res) => {
assertEquals(req.headers["x-foo"], "bar");
res.end("ok");
@ -249,7 +248,7 @@ Deno.test("[node/http] request with headers", async () => {
req.end();
});
server.on("close", () => {
promise.resolve();
resolve();
});
await promise;
});
@ -258,7 +257,7 @@ Deno.test("[node/http] non-string buffer response", {
// TODO(kt3k): Enable sanitizer. A "zlib" resource is leaked in this test case.
sanitizeResources: false,
}, async () => {
const promise = deferred<void>();
const { promise, resolve } = Promise.withResolvers<void>();
const server = http.createServer((_, res) => {
res.socket!.end();
gzip(
@ -281,7 +280,7 @@ Deno.test("[node/http] non-string buffer response", {
} catch (e) {
server.emit("error", e);
} finally {
server.close(() => promise.resolve());
server.close(() => resolve());
}
});
await promise;
@ -461,7 +460,7 @@ Deno.test("[node/http] send request with chunked body as default", async () => {
});
Deno.test("[node/http] ServerResponse _implicitHeader", async () => {
const d = deferred<void>();
const { promise, resolve } = Promise.withResolvers<void>();
const server = http.createServer((_req, res) => {
const writeHeadSpy = spy(res, "writeHead");
// deno-lint-ignore no-explicit-any
@ -476,11 +475,11 @@ Deno.test("[node/http] ServerResponse _implicitHeader", async () => {
const res = await fetch(`http://localhost:${port}`);
assertEquals(await res.text(), "Hello World");
server.close(() => {
d.resolve();
resolve();
});
});
await d;
await promise;
});
Deno.test("[node/http] server unref", async () => {
@ -504,7 +503,7 @@ Deno.test("[node/http] server unref", async () => {
Deno.test("[node/http] ClientRequest handle non-string headers", async () => {
// deno-lint-ignore no-explicit-any
let headers: any;
const def = deferred();
const { promise, resolve, reject } = Promise.withResolvers<void>();
const req = http.request("http://localhost:4545/echo_server", {
method: "POST",
headers: { 1: 2 },
@ -514,18 +513,18 @@ Deno.test("[node/http] ClientRequest handle non-string headers", async () => {
resp.on("data", () => {});
resp.on("end", () => {
def.resolve();
resolve();
});
});
req.once("error", (e) => def.reject(e));
req.once("error", (e) => reject(e));
req.end();
await def;
await promise;
assertEquals(headers!["1"], "2");
});
Deno.test("[node/http] ClientRequest uses HTTP/1.1", async () => {
let body = "";
const def = deferred();
const { promise, resolve, reject } = Promise.withResolvers<void>();
const req = https.request("https://localhost:5545/http_version", {
method: "POST",
headers: { 1: 2 },
@ -535,39 +534,39 @@ Deno.test("[node/http] ClientRequest uses HTTP/1.1", async () => {
});
resp.on("end", () => {
def.resolve();
resolve();
});
});
req.once("error", (e) => def.reject(e));
req.once("error", (e) => reject(e));
req.end();
await def;
await promise;
assertEquals(body, "HTTP/1.1");
});
Deno.test("[node/http] ClientRequest setTimeout", async () => {
let body = "";
const def = deferred();
const timer = setTimeout(() => def.reject("timed out"), 50000);
const { promise, resolve, reject } = Promise.withResolvers<void>();
const timer = setTimeout(() => reject("timed out"), 50000);
const req = http.request("http://localhost:4545/http_version", (resp) => {
resp.on("data", (chunk) => {
body += chunk;
});
resp.on("end", () => {
def.resolve();
resolve();
});
});
req.setTimeout(120000);
req.once("error", (e) => def.reject(e));
req.once("error", (e) => reject(e));
req.end();
await def;
await promise;
clearTimeout(timer);
assertEquals(body, "HTTP/1.1");
});
Deno.test("[node/http] ClientRequest PATCH", async () => {
let body = "";
const def = deferred();
const { promise, resolve, reject } = Promise.withResolvers<void>();
const req = http.request("http://localhost:4545/echo_server", {
method: "PATCH",
}, (resp) => {
@ -576,20 +575,20 @@ Deno.test("[node/http] ClientRequest PATCH", async () => {
});
resp.on("end", () => {
def.resolve();
resolve();
});
});
req.write("hello ");
req.write("world");
req.once("error", (e) => def.reject(e));
req.once("error", (e) => reject(e));
req.end();
await def;
await promise;
assertEquals(body, "hello world");
});
Deno.test("[node/http] ClientRequest PUT", async () => {
let body = "";
const def = deferred();
const { promise, resolve, reject } = Promise.withResolvers<void>();
const req = http.request("http://localhost:4545/echo_server", {
method: "PUT",
}, (resp) => {
@ -598,20 +597,20 @@ Deno.test("[node/http] ClientRequest PUT", async () => {
});
resp.on("end", () => {
def.resolve();
resolve();
});
});
req.write("hello ");
req.write("world");
req.once("error", (e) => def.reject(e));
req.once("error", (e) => reject(e));
req.end();
await def;
await promise;
assertEquals(body, "hello world");
});
Deno.test("[node/http] ClientRequest search params", async () => {
let body = "";
const def = deferred();
const { promise, resolve, reject } = Promise.withResolvers<void>();
const req = http.request({
host: "localhost:4545",
path: "search_params?foo=bar",
@ -621,18 +620,18 @@ Deno.test("[node/http] ClientRequest search params", async () => {
});
resp.on("end", () => {
def.resolve();
resolve();
});
});
req.once("error", (e) => def.reject(e));
req.once("error", (e) => reject(e));
req.end();
await def;
await promise;
assertEquals(body, "foo=bar");
});
Deno.test("[node/http] HTTPS server", async () => {
const promise = deferred<void>();
const promise2 = deferred<void>();
const deferred = Promise.withResolvers<void>();
const deferred2 = Promise.withResolvers<void>();
const client = Deno.createHttpClient({
caCerts: [Deno.readTextFileSync("cli/tests/testdata/tls/RootCA.pem")],
});
@ -652,14 +651,14 @@ Deno.test("[node/http] HTTPS server", async () => {
assertEquals(res.status, 200);
assertEquals(await res.text(), "success!");
server.close();
promise2.resolve();
deferred2.resolve();
});
})
.on("error", () => fail());
server.on("close", () => {
promise.resolve();
deferred.resolve();
});
await Promise.all([promise, promise2]);
await Promise.all([deferred.promise, deferred2.promise]);
client.close();
});
@ -667,7 +666,7 @@ Deno.test(
"[node/http] client upgrade",
{ permissions: { net: true } },
async () => {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
const server = http.createServer((req, res) => {
// @ts-ignore: It exists on TLSSocket
assert(!req.socket.encrypted);
@ -706,7 +705,7 @@ Deno.test(
// @ts-ignore it's a socket for real
serverSocket!.end();
server.close(() => {
promise.resolve();
resolve();
});
});
});
@ -725,7 +724,7 @@ Deno.test(
received = true;
return new Response("hello");
});
const promise = deferred();
const { promise, resolve, reject } = Promise.withResolvers<void>();
let body = "";
const request = http.request(
@ -736,11 +735,11 @@ Deno.test(
});
resp.on("end", () => {
promise.resolve();
resolve();
});
},
);
request.on("error", promise.reject);
request.on("error", reject);
request.end(() => {
assert(received);
});
@ -754,22 +753,22 @@ Deno.test(
);
Deno.test("[node/http] server emits error if addr in use", async () => {
const promise = deferred<void>();
const promise2 = deferred<Error>();
const deferred1 = Promise.withResolvers<void>();
const deferred2 = Promise.withResolvers<Error>();
const server = http.createServer();
server.listen(9001);
const server2 = http.createServer();
server2.on("error", (e) => {
promise2.resolve(e);
deferred2.resolve(e);
});
server2.listen(9001);
const err = await promise2;
server.close(() => promise.resolve());
const err = await deferred2.promise;
server.close(() => deferred1.resolve());
server2.close();
await promise;
await deferred1.promise;
const expectedMsg = Deno.build.os === "windows"
? "Only one usage of each socket address"
: "Address already in use";
@ -795,15 +794,15 @@ Deno.test(
return new Response("hello");
},
);
const promise = deferred();
const { promise, resolve, reject } = Promise.withResolvers<void>();
const request = http.request("http://localhost:5929/");
request.on("error", promise.reject);
request.on("error", reject);
request.on("close", () => {});
request.end();
setTimeout(() => {
request.destroy(new Error());
promise.resolve();
resolve();
}, 100);
await promise;

View file

@ -6,7 +6,6 @@ import {
assertNotEquals,
assertThrows,
} from "../../../../test_util/std/testing/asserts.ts";
import { deferred } from "../../../../test_util/std/async/deferred.ts";
const validateNonZero = (buf: Buffer) => {
if (!buf.some((ch) => ch > 0)) throw new Error("Error");
@ -17,14 +16,14 @@ const validateZero = (buf: Buffer) => {
};
Deno.test("[node/crypto.randomFill]", async () => {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<boolean>();
const buf = Buffer.alloc(10);
const before = buf.toString("hex");
randomFill(buf, 5, 5, (_err, bufTwo) => {
const after = bufTwo?.toString("hex");
assertEquals(before.slice(0, 10), after?.slice(0, 10));
promise.resolve(true);
resolve(true);
});
await promise;

View file

@ -2,10 +2,9 @@
import { scrypt, scryptSync } from "node:crypto";
import { Buffer } from "node:buffer";
import { assertEquals } from "../../../../test_util/std/testing/asserts.ts";
import { deferred } from "../../../../test_util/std/async/deferred.ts";
Deno.test("scrypt works correctly", async () => {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<boolean>();
scrypt("password", "salt", 32, (err, key) => {
if (err) throw err;
@ -46,14 +45,14 @@ Deno.test("scrypt works correctly", async () => {
115,
]),
);
promise.resolve(true);
resolve(true);
});
await promise;
});
Deno.test("scrypt works with options", async () => {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<boolean>();
scrypt(
"password",
@ -101,7 +100,7 @@ Deno.test("scrypt works with options", async () => {
71,
]),
);
promise.resolve(true);
resolve(true);
},
);

View file

@ -5,15 +5,14 @@ import {
assert,
assertEquals,
} from "../../../test_util/std/testing/asserts.ts";
import { Deferred, deferred } from "../../../test_util/std/async/deferred.ts";
import * as path from "../../../test_util/std/path/mod.ts";
import * as http from "node:http";
Deno.test("[node/net] close event emits after error event", async () => {
const socket = net.createConnection(27009, "doesnotexist");
const events: ("error" | "close")[] = [];
const errorEmitted = deferred();
const closeEmitted = deferred();
const errorEmitted = Promise.withResolvers<void>();
const closeEmitted = Promise.withResolvers<void>();
socket.once("error", () => {
events.push("error");
errorEmitted.resolve();
@ -22,14 +21,14 @@ Deno.test("[node/net] close event emits after error event", async () => {
events.push("close");
closeEmitted.resolve();
});
await Promise.all([errorEmitted, closeEmitted]);
await Promise.all([errorEmitted.promise, closeEmitted.promise]);
// `error` happens before `close`
assertEquals(events, ["error", "close"]);
});
Deno.test("[node/net] the port is available immediately after close callback", async () => {
const p = deferred();
const deferred = Promise.withResolvers<void>();
// This simulates what get-port@5.1.1 does.
const getAvailablePort = (port: number) =>
@ -48,11 +47,11 @@ Deno.test("[node/net] the port is available immediately after close callback", a
const port = await getAvailablePort(5555);
const httpServer = http.createServer();
httpServer.on("error", (e) => p.reject(e));
httpServer.on("error", (e) => deferred.reject(e));
httpServer.listen(port, () => {
httpServer.close(() => p.resolve());
httpServer.close(() => deferred.resolve());
});
await p;
await deferred.promise;
});
Deno.test("[node/net] net.connect().unref() works", async () => {
@ -100,16 +99,16 @@ Deno.test({
});
Deno.test("[node/net] connection event has socket value", async () => {
const p = deferred();
const p2 = deferred();
const deferred = Promise.withResolvers<void>();
const deferred2 = Promise.withResolvers<void>();
const server = net.createServer();
server.on("error", p.reject);
server.on("error", deferred.reject);
server.on("connection", (socket) => {
assert(socket !== undefined);
socket.end();
server.close(() => {
p.resolve();
deferred.resolve();
});
});
server.listen(async () => {
@ -125,10 +124,10 @@ Deno.test("[node/net] connection event has socket value", async () => {
//
}
p2.resolve();
deferred2.resolve();
});
await Promise.all([p, p2]);
await Promise.all([deferred.promise, deferred2.promise]);
});
/// We need to make sure that any shared buffers are never used concurrently by two reads.
@ -137,17 +136,19 @@ Deno.test("[node/net] multiple Sockets should get correct server data", async ()
const socketCount = 9;
class TestSocket {
dataReceived: Deferred<undefined> = deferred();
dataReceived: ReturnType<typeof Promise.withResolvers<void>> = Promise
.withResolvers<void>();
events: string[] = [];
socket: net.Socket | undefined;
}
const finished = deferred();
const serverSocketsClosed: Deferred<undefined>[] = [];
const finished = Promise.withResolvers<void>();
const serverSocketsClosed: ReturnType<typeof Promise.withResolvers<void>>[] =
[];
const server = net.createServer();
server.on("connection", (socket) => {
assert(socket !== undefined);
const i = serverSocketsClosed.push(deferred());
const i = serverSocketsClosed.push(Promise.withResolvers<void>());
socket.on("data", (data) => {
socket.write(new TextDecoder().decode(data));
});
@ -183,7 +184,7 @@ Deno.test("[node/net] multiple Sockets should get correct server data", async ()
sockets[i].socket?.write(`${i}`.repeat(3));
}
await Promise.all(sockets.map((socket) => socket.dataReceived));
await Promise.all(sockets.map((socket) => socket.dataReceived.promise));
for (let i = 0; i < socketCount; i++) {
sockets[i].socket?.end();
@ -194,8 +195,8 @@ Deno.test("[node/net] multiple Sockets should get correct server data", async ()
});
});
await finished;
await Promise.all(serverSocketsClosed);
await finished.promise;
await Promise.all(serverSocketsClosed.map(({ promise }) => promise));
for (let i = 0; i < socketCount; i++) {
assertEquals(sockets[i].events, [`${i}`.repeat(3), `${i}`.repeat(3)]);

View file

@ -13,7 +13,6 @@ import {
assertThrows,
} from "../../../test_util/std/testing/asserts.ts";
import { stripColor } from "../../../test_util/std/fmt/colors.ts";
import { deferred } from "../../../test_util/std/async/deferred.ts";
import * as path from "../../../test_util/std/path/mod.ts";
import { delay } from "../../../test_util/std/async/delay.ts";
@ -368,7 +367,7 @@ Deno.test({
// stdin resource is present before the test starts.
sanitizeResources: false,
async fn() {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
const expected = ["foo", "bar", null, "end"];
const data: (string | null)[] = [];
@ -385,7 +384,7 @@ Deno.test({
process.stdin.push("bar");
process.nextTick(() => {
process.stdin.push(null);
promise.resolve();
resolve();
});
});

View file

@ -5,7 +5,6 @@ import {
assertInstanceOf,
} from "../../../test_util/std/testing/asserts.ts";
import { delay } from "../../../test_util/std/async/delay.ts";
import { deferred } from "../../../test_util/std/async/deferred.ts";
import { fromFileUrl, join } from "../../../test_util/std/path/mod.ts";
import { serveTls } from "../../../test_util/std/http/server.ts";
import * as tls from "node:tls";
@ -89,7 +88,7 @@ Deno.test("tls.connect mid-read tcp->tls upgrade", async () => {
});
Deno.test("tls.createServer creates a TLS server", async () => {
const p = deferred();
const deferred = Promise.withResolvers<void>();
const server = tls.createServer(
// deno-lint-ignore no-explicit-any
{ host: "0.0.0.0", key, cert } as any,
@ -131,9 +130,9 @@ Deno.test("tls.createServer creates a TLS server", async () => {
conn.close();
server.close();
p.resolve();
deferred.resolve();
});
await p;
await deferred.promise;
});
Deno.test("TLSSocket can construct without options", () => {

View file

@ -4,7 +4,6 @@ import {
assert,
assertEquals,
} from "../../../test_util/std/testing/asserts.ts";
import { deferred } from "../../../test_util/std/async/deferred.ts";
import { fromFileUrl, relative } from "../../../test_util/std/path/mod.ts";
import {
brotliCompressSync,
@ -24,7 +23,7 @@ Deno.test("brotli compression sync", () => {
});
Deno.test("brotli compression", async () => {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
const compress = createBrotliCompress();
const filePath = relative(
Deno.cwd(),
@ -43,7 +42,7 @@ Deno.test("brotli compression", async () => {
const stream2 = input2.pipe(decompress).pipe(output2);
stream2.on("finish", () => {
promise.resolve();
resolve();
});
});
@ -73,12 +72,12 @@ Deno.test(
"zlib create deflate with dictionary",
{ sanitizeResources: false },
async () => {
const promise = deferred();
const { promise, resolve } = Promise.withResolvers<void>();
const handle = createDeflate({
dictionary: Buffer.alloc(0),
});
handle.on("close", () => promise.resolve());
handle.on("close", () => resolve());
handle.end();
handle.destroy();

View file

@ -1,39 +1,10 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// This module is vendored from std/async/deferred.ts and std/async/delay.ts
// This module is vendored from std/async/delay.ts
// (with some modifications)
// TODO(petamoriken): enable prefer-primordials for node polyfills
// deno-lint-ignore-file prefer-primordials
export interface Deferred<T> extends Promise<T> {
readonly state: "pending" | "fulfilled" | "rejected";
resolve(value?: T | PromiseLike<T>): void;
// deno-lint-ignore no-explicit-any
reject(reason?: any): void;
}
/** Creates a Promise with the `reject` and `resolve` functions */
export function deferred<T>(): Deferred<T> {
let methods;
let state = "pending";
const promise = new Promise<T>((resolve, reject) => {
methods = {
async resolve(value: T | PromiseLike<T>) {
await value;
state = "fulfilled";
resolve(value);
},
// deno-lint-ignore no-explicit-any
reject(reason?: any) {
state = "rejected";
reject(reason);
},
};
});
Object.defineProperty(promise, "state", { get: () => state });
return Object.assign(promise, methods) as Deferred<T>;
}
/** Resolve a Promise after a given amount of milliseconds. */
export function delay(
ms: number,

View file

@ -7,7 +7,6 @@
const core = globalThis.__bootstrap.core;
import { TextEncoder } from "ext:deno_web/08_text_encoding.js";
import { type Deferred, deferred } from "ext:deno_node/_util/async.ts";
import { setTimeout } from "ext:deno_web/02_timers.js";
import {
_normalizeArgs,
@ -1556,7 +1555,7 @@ export class ServerImpl extends EventEmitter {
#server: Deno.Server;
#unref = false;
#ac?: AbortController;
#servePromise: Deferred<void>;
#serveDeferred: ReturnType<typeof Promise.withResolvers<void>>;
listening = false;
constructor(opts, requestListener?: ServerHandler) {
@ -1573,8 +1572,8 @@ export class ServerImpl extends EventEmitter {
this._opts = opts;
this.#servePromise = deferred();
this.#servePromise.then(() => this.emit("close"));
this.#serveDeferred = Promise.withResolvers<void>();
this.#serveDeferred.promise.then(() => this.emit("close"));
if (requestListener !== undefined) {
this.on("request", requestListener);
}
@ -1660,7 +1659,7 @@ export class ServerImpl extends EventEmitter {
if (this.#unref) {
this.#server.unref();
}
this.#server.finished.then(() => this.#servePromise!.resolve());
this.#server.finished.then(() => this.#serveDeferred!.resolve());
}
setTimeout() {
@ -1700,7 +1699,7 @@ export class ServerImpl extends EventEmitter {
this.#ac.abort();
this.#ac = undefined;
} else {
this.#servePromise!.resolve();
this.#serveDeferred!.resolve();
}
this.#server = undefined;

View file

@ -20,7 +20,6 @@ import {
import { FileHandle } from "node:fs/promises";
import { kStreamBaseField } from "ext:deno_node/internal_binding/stream_wrap.ts";
import { addTrailers, serveHttpOnConnection } from "ext:deno_http/00_serve.js";
import { type Deferred, deferred } from "ext:deno_node/_util/async.ts";
import { nextTick } from "ext:deno_node/_next_tick.ts";
import { TextEncoder } from "ext:deno_web/08_text_encoding.js";
import { Duplex } from "node:stream";
@ -552,9 +551,9 @@ function getAuthority(headers) {
export class Http2Stream extends EventEmitter {
#session: Http2Session;
#headers: Deferred<Http2Headers>;
#controllerPromise: Deferred<ReadableStreamDefaultController<Uint8Array>>;
#readerPromise: Deferred<ReadableStream<Uint8Array>>;
#headers: Promise<Http2Headers>;
#controllerPromise: Promise<ReadableStreamDefaultController<Uint8Array>>;
#readerPromise: Promise<ReadableStream<Uint8Array>>;
#closed: boolean;
_response: Response;
@ -1260,7 +1259,7 @@ function callTimeout() {
}
export class ServerHttp2Stream extends Http2Stream {
_promise: Deferred<Response>;
_deferred: ReturnType<typeof Promise.withResolvers<Response>>;
#body: ReadableStream<Uint8Array>;
#waitForTrailers: boolean;
#headersSent: boolean;
@ -1273,7 +1272,7 @@ export class ServerHttp2Stream extends Http2Stream {
body: ReadableStream<Uint8Array>,
) {
super(session, headers, controllerPromise, Promise.resolve(reader));
this._promise = new deferred();
this._deferred = Promise.withResolvers<Response>();
this.#body = body;
}
@ -1319,10 +1318,10 @@ export class ServerHttp2Stream extends Http2Stream {
}
}
if (options?.endStream) {
this._promise.resolve(this._response = new Response("", response));
this._deferred.resolve(this._response = new Response("", response));
} else {
this.#waitForTrailers = options?.waitForTrailers;
this._promise.resolve(
this._deferred.resolve(
this._response = new Response(this.#body, response),
);
}
@ -1368,12 +1367,12 @@ export class Http2Server extends Server {
this.#abortController.signal,
async (req: Request) => {
try {
const controllerPromise: Deferred<
const controllerDeferred = Promise.withResolvers<
ReadableStreamDefaultController<Uint8Array>
> = deferred();
>();
const body = new ReadableStream({
start(controller) {
controllerPromise.resolve(controller);
controllerDeferred.resolve(controller);
},
});
const headers: Http2Headers = {};
@ -1385,13 +1384,13 @@ export class Http2Server extends Server {
const stream = new ServerHttp2Stream(
session,
Promise.resolve(headers),
controllerPromise,
controllerDeferred.promise,
req.body,
body,
);
session.emit("stream", stream, headers);
this.emit("stream", stream, headers);
return await stream._promise;
return await stream._deferred.promise;
} catch (e) {
console.log(">>> Error in serveHttpOnConnection", e);
}

View file

@ -11,7 +11,6 @@ import { EventEmitter } from "node:events";
import { os } from "ext:deno_node/internal_binding/constants.ts";
import { notImplemented, warnNotImplemented } from "ext:deno_node/_utils.ts";
import { Readable, Stream, Writable } from "node:stream";
import { deferred } from "ext:deno_node/_util/async.ts";
import { isWindows } from "ext:deno_node/_util/os.ts";
import { nextTick } from "ext:deno_node/_next_tick.ts";
import {
@ -151,7 +150,7 @@ export class ChildProcess extends EventEmitter {
];
#process!: Deno.ChildProcess;
#spawned = deferred<void>();
#spawned = Promise.withResolvers<void>();
constructor(
command: string,
@ -253,7 +252,7 @@ export class ChildProcess extends EventEmitter {
(async () => {
const status = await this.#process.status;
this.exitCode = status.code;
this.#spawned.then(async () => {
this.#spawned.promise.then(async () => {
const exitCode = this.signalCode == null ? this.exitCode : null;
const signalCode = this.signalCode == null ? null : this.signalCode;
// The 'exit' and 'close' events must be emitted after the 'spawn' event.
@ -688,22 +687,22 @@ function waitForReadableToClose(readable: Readable) {
}
function waitForStreamToClose(stream: Stream) {
const promise = deferred<void>();
const deferred = Promise.withResolvers<void>();
const cleanup = () => {
stream.removeListener("close", onClose);
stream.removeListener("error", onError);
};
const onClose = () => {
cleanup();
promise.resolve();
deferred.resolve();
};
const onError = (err: Error) => {
cleanup();
promise.reject(err);
deferred.reject(err);
};
stream.once("close", onClose);
stream.once("error", onError);
return promise;
return deferred.promise;
}
/**

View file

@ -5,23 +5,6 @@
import { notImplemented, warnNotImplemented } from "ext:deno_node/_utils.ts";
export function deferred() {
let methods;
const promise = new Promise((resolve, reject) => {
methods = {
async resolve(value) {
await value;
resolve(value);
},
// deno-lint-ignore no-explicit-any
reject(reason?: any) {
reject(reason);
},
};
});
return Object.assign(promise, methods);
}
export function run() {
notImplemented("test.run");
}
@ -124,13 +107,13 @@ function prepareOptions(name, options, fn, overrides) {
return { fn, options: finalOptions, name };
}
function wrapTestFn(fn, promise) {
function wrapTestFn(fn, resolve) {
return async function (t) {
const nodeTestContext = new NodeTestContext(t);
try {
await fn(nodeTestContext);
} finally {
promise.resolve(undefined);
resolve();
}
};
}
@ -138,11 +121,11 @@ function wrapTestFn(fn, promise) {
function prepareDenoTest(name, options, fn, overrides) {
const prepared = prepareOptions(name, options, fn, overrides);
const promise = deferred();
const { promise, resolve } = Promise.withResolvers();
const denoTestOptions = {
name: prepared.name,
fn: wrapTestFn(prepared.fn, promise),
fn: wrapTestFn(prepared.fn, resolve),
only: prepared.options.only,
ignore: prepared.options.todo || prepared.options.skip,
};

View file

@ -482,30 +482,12 @@ function test_fill_buffer(fillValue, arr) {
test_fill_buffer(0, [2, 3, 4]);
test_fill_buffer(5, [2, 7, 3, 2, 1]);
// Test non blocking calls
function deferred() {
let methods;
const promise = new Promise((resolve, reject) => {
methods = {
async resolve(value) {
await value;
resolve(value);
},
reject(reason) {
reject(reason);
},
};
});
return Object.assign(promise, methods);
}
const promise = deferred();
const deferred = Promise.withResolvers();
const buffer3 = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
dylib.symbols.nonblocking_buffer(buffer3, buffer3.length).then(() => {
promise.resolve();
deferred.resolve();
});
await promise;
await deferred.promise;
let start = performance.now();
dylib.symbols.sleep_blocking(100);

View file

@ -1,5 +1,4 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
import { deferred } from "../test_util/std/async/deferred.ts";
import {
dirname,
fromFileUrl,
@ -182,10 +181,10 @@ const downloadUrl =
export async function downloadPrebuilt(toolName) {
// Ensure only one download per tool happens at a time
if (DOWNLOAD_TASKS[toolName]) {
return await DOWNLOAD_TASKS[toolName];
return await DOWNLOAD_TASKS[toolName].promise;
}
const downloadPromise = DOWNLOAD_TASKS[toolName] = deferred();
const downloadDeferred = DOWNLOAD_TASKS[toolName] = Promise.withResolvers();
const spinner = wait({
text: "Downloading prebuilt tool: " + toolName,
interval: 1000,
@ -230,12 +229,12 @@ export async function downloadPrebuilt(toolName) {
await Deno.rename(tempFile, toolPath);
} catch (e) {
spinner.fail();
downloadPromise.reject(e);
downloadDeferred.reject(e);
throw e;
}
spinner.succeed();
downloadPromise.resolve(null);
downloadDeferred.resolve(null);
}
export async function verifyVersion(toolName, toolPath) {