File tree Expand file tree Collapse file tree 3 files changed +45
-0
lines changed Expand file tree Collapse file tree 3 files changed +45
-0
lines changed Original file line number Diff line number Diff line change 6
6
"./async-value" : " ./async_value.ts" ,
7
7
"./barrier" : " ./barrier.ts" ,
8
8
"./ensure-promise" : " ./ensure_promise.ts" ,
9
+ "./flush-promises" : " ./flush_promises.ts" ,
9
10
"./lock" : " ./lock.ts" ,
10
11
"./mutex" : " ./mutex.ts" ,
11
12
"./notify" : " ./notify.ts" ,
36
37
"@core/asyncutil/async-value" : " ./async_value.ts" ,
37
38
"@core/asyncutil/barrier" : " ./barrier.ts" ,
38
39
"@core/asyncutil/ensure-promise" : " ./ensure_promise.ts" ,
40
+ "@core/asyncutil/flush-promises" : " ./flush_promises.ts" ,
39
41
"@core/asyncutil/lock" : " ./lock.ts" ,
40
42
"@core/asyncutil/mutex" : " ./mutex.ts" ,
41
43
"@core/asyncutil/notify" : " ./notify.ts" ,
Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change
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
+ ) ;
You can’t perform that action at this time.
0 commit comments