From cd7a48b90b611a2f80c7aa5dc4eb7f3b0b122794 Mon Sep 17 00:00:00 2001 From: Alisue Date: Tue, 20 Aug 2024 13:04:01 +0900 Subject: [PATCH] feat(flushPromises): add `flushPromises` function --- README.md | 21 +++++++++++++++++++++ deno.jsonc | 2 ++ flush_promises.ts | 23 +++++++++++++++++++++++ flush_promises_test.ts | 18 ++++++++++++++++++ 4 files changed, 64 insertions(+) create mode 100644 flush_promises.ts create mode 100644 flush_promises_test.ts diff --git a/README.md b/README.md index 29542a5..ddd03cd 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,27 @@ worker(2); worker(3); ``` +### flushPromises + +`flushPromises` waits all pending promises to be resolved. + +```ts +import { flushPromises } from "@core/asyncutil/flush-promises"; + +let count = 0; +Array.from({ length: 10 }).forEach(() => { + new Promise((resolve) => resolve()).then(() => { + count++; + }); +}); + +console.log(count); // 0 + +await flushPromises(); + +console.log(count); // 10 +``` + ### Lock/RwLock `Lock` is a mutual exclusion lock that provides safe concurrent access to a diff --git a/deno.jsonc b/deno.jsonc index 67aa3d3..36815e4 100644 --- a/deno.jsonc +++ b/deno.jsonc @@ -5,6 +5,7 @@ ".": "./mod.ts", "./async-value": "./async_value.ts", "./barrier": "./barrier.ts", + "./flush-promises": "./flush_promises.ts", "./lock": "./lock.ts", "./mutex": "./mutex.ts", "./notify": "./notify.ts", @@ -34,6 +35,7 @@ "@core/asyncutil": "./mod.ts", "@core/asyncutil/async-value": "./async_value.ts", "@core/asyncutil/barrier": "./barrier.ts", + "@core/asyncutil/flush-promises": "./flush_promises.ts", "@core/asyncutil/lock": "./lock.ts", "@core/asyncutil/mutex": "./mutex.ts", "@core/asyncutil/notify": "./notify.ts", diff --git a/flush_promises.ts b/flush_promises.ts new file mode 100644 index 0000000..fa38d81 --- /dev/null +++ b/flush_promises.ts @@ -0,0 +1,23 @@ +/** + * Flushes all pending promises. + * + * ```ts + * import { flushPromises } from "@core/asyncutil/flush-promises"; + * + * let count = 0; + * Array.from({ length: 10 }).forEach(() => { + * new Promise((resolve) => resolve()).then(() => { + * count++; + * }); + * }); + * + * console.log(count); // 0 + * + * await flushPromises(); + * + * console.log(count); // 10 + * ``` + */ +export function flushPromises(): Promise { + return new Promise((resolve) => setTimeout(resolve)); +} diff --git a/flush_promises_test.ts b/flush_promises_test.ts new file mode 100644 index 0000000..2ef112c --- /dev/null +++ b/flush_promises_test.ts @@ -0,0 +1,18 @@ +import { test } from "@cross/test"; +import { assertEquals } from "@std/assert"; +import { flushPromises } from "./flush_promises.ts"; + +test( + "flushPromises() wait all promises are resolves", + async () => { + let count = 0; + Array.from({ length: 10 }).forEach(() => { + new Promise((resolve) => resolve()).then(() => { + count++; + }); + }); + assertEquals(count, 0); + await flushPromises(); + assertEquals(count, 10); + }, +);