Skip to content

Commit

Permalink
fix(delay): resolve value
Browse files Browse the repository at this point in the history
  • Loading branch information
fupengl committed Jul 6, 2023
1 parent 2924ce7 commit 2af4076
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 3 deletions.
22 changes: 22 additions & 0 deletions __tests__/promise/async-pool.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { asyncPool, delay } from '../../src/promise';

describe('promise/asyncPool', () => {
test('should be executed one by one', async function () {
const pool = asyncPool({ maxConcurrency: 1 });
const start = Date.now();
pool.executor(() => delay(100));
pool.executor(() => delay(100));
await pool.executor(() => delay(100));
expect(Date.now() - start).toBeGreaterThanOrEqual(300);
});

test('should be executed concurrently', async function () {
const pool = asyncPool({ maxConcurrency: 3 });
const start = Date.now();
pool.executor(() => delay(100));
pool.executor(() => delay(100));
await pool.executor(() => delay(100));
// If the timer is inaccurate, add 10 to the safety range
expect(Date.now() - start).toBeLessThanOrEqual(110);
});
});
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { memoize, delay } from '../src/promise';
import { memoize, delay } from '../../src/promise';

describe('promise/memoize', () => {
test('cache 1000ms', async () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { timeout, delay } from '../src/promise';
import { timeout, delay } from '../../src/promise';

describe('promise/timeout', () => {
test('resolves appropriate value when function finishes first', async () => {
Expand Down
2 changes: 1 addition & 1 deletion src/promise/delay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ async function delay<T>(delayTimeMs: number, value: T): Promise<T>;
async function delay<T>(delayTimeMs: number): Promise<void>;
async function delay<T>(delayTime: number, value?: T): Promise<void | T> {
if (delayTime <= 17) {
return new Promise((resolve) => requestAnimationFrame(() => resolve()));
return new Promise((resolve) => requestAnimationFrame(() => resolve(value)));
}
return new Promise((resolve) => setTimeout(() => resolve(value), delayTime));
}
Expand Down

0 comments on commit 2af4076

Please sign in to comment.