Skip to content

Commit

Permalink
feat(flushPromises): add flushPromises function
Browse files Browse the repository at this point in the history
  • Loading branch information
lambdalisue committed Aug 20, 2024
1 parent 686fd39 commit cd7a48b
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 0 deletions.
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<void>((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
Expand Down
2 changes: 2 additions & 0 deletions deno.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down
23 changes: 23 additions & 0 deletions flush_promises.ts
Original file line number Diff line number Diff line change
@@ -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<void>((resolve) => resolve()).then(() => {
* count++;
* });
* });
*
* console.log(count); // 0
*
* await flushPromises();
*
* console.log(count); // 10
* ```
*/
export function flushPromises(): Promise<void> {
return new Promise((resolve) => setTimeout(resolve));
}
18 changes: 18 additions & 0 deletions flush_promises_test.ts
Original file line number Diff line number Diff line change
@@ -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<void>((resolve) => resolve()).then(() => {
count++;
});
});
assertEquals(count, 0);
await flushPromises();
assertEquals(count, 10);
},
);

0 comments on commit cd7a48b

Please sign in to comment.