Skip to content

Commit bf50477

Browse files
committed
feat(flushPromises): add flushPromises function
1 parent 5950811 commit bf50477

File tree

3 files changed

+45
-0
lines changed

3 files changed

+45
-0
lines changed

deno.jsonc

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
"./async-value": "./async_value.ts",
77
"./barrier": "./barrier.ts",
88
"./ensure-promise": "./ensure_promise.ts",
9+
"./flush-promises": "./flush_promises.ts",
910
"./lock": "./lock.ts",
1011
"./mutex": "./mutex.ts",
1112
"./notify": "./notify.ts",
@@ -36,6 +37,7 @@
3637
"@core/asyncutil/async-value": "./async_value.ts",
3738
"@core/asyncutil/barrier": "./barrier.ts",
3839
"@core/asyncutil/ensure-promise": "./ensure_promise.ts",
40+
"@core/asyncutil/flush-promises": "./flush_promises.ts",
3941
"@core/asyncutil/lock": "./lock.ts",
4042
"@core/asyncutil/mutex": "./mutex.ts",
4143
"@core/asyncutil/notify": "./notify.ts",

flush_promises.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* Flush all pending promises in the microtask queue.
3+
*
4+
* ```ts
5+
* import { flushPromises } from "@core/asyncutil/flush-promises";
6+
*
7+
* let count = 0;
8+
* Array.from({ length: 5 }).forEach(() => {
9+
* Promise.resolve()
10+
* .then(() => count++)
11+
* .then(() => count++);
12+
* });
13+
*
14+
* console.log(count); // 0
15+
* await flushPromises();
16+
* console.log(count); // 10
17+
* ```
18+
*
19+
* The original idea comes from [flush-promises] package in npm.
20+
*
21+
* [flush-promises]: https://www.npmjs.com/package/flush-promises
22+
*/
23+
export function flushPromises(): Promise<void> {
24+
return new Promise((resolve) => setTimeout(resolve));
25+
}

flush_promises_test.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import { test } from "@cross/test";
2+
import { assertEquals } from "@std/assert";
3+
import { flushPromises } from "./flush_promises.ts";
4+
5+
test(
6+
"flushPromises() flushes all pending promises in the microtask queue",
7+
async () => {
8+
let count = 0;
9+
Array.from({ length: 5 }).forEach(() => {
10+
Promise.resolve()
11+
.then(() => count++)
12+
.then(() => count++);
13+
});
14+
assertEquals(count, 0);
15+
await flushPromises();
16+
assertEquals(count, 10);
17+
},
18+
);

0 commit comments

Comments
 (0)