Skip to content

Commit

Permalink
fix: bug when throttled function is sync
Browse files Browse the repository at this point in the history
fix #11
  • Loading branch information
jedwards1211 committed Dec 8, 2020
1 parent 947f638 commit ad364ff
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 3 deletions.
10 changes: 8 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ class Delay {
}

function throttle<Args: Array<any>, Value>(
fn: (...args: Args) => Promise<Value>,
fn: (...args: Args) => Value | Promise<Value>,
_wait: ?number,
options: {
getNextArgs?: (args0: Args, args1: Args) => Args,
Expand All @@ -52,10 +52,16 @@ function throttle<Args: Array<any>, Value>(

function invoke(): Promise<Value> {
const args = nextArgs
// istanbul ignore next
if (!args) throw new Error('unexpected error: nextArgs is null')
nextInvocation = null
nextArgs = null
const result = fn(...args)
let result
try {
result = Promise.resolve(fn(...args))
} catch (error) {
result = Promise.reject(error)
}
lastInvocationDone = result.catch(() => {})
delay = new Delay(lastInvocationDone, wait)
return result
Expand Down
38 changes: 37 additions & 1 deletion test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,43 @@ describe('throttle', () => {
getNextArgs: () => (null: any),
})
fn(1)
expect(() => fn(1)).to.throw()
expect(() => fn(1)).to.throw('unexpected error: nextArgs is null')
})
it('works with sync function', async function(): Promise<void> {
const foo = sinon.spy(
(a: number, wait?: number): number => {
if (a < 0) throw new Error()
return a * 2
}
)
const fn = throttle(foo, 100)
let promises = [fn(1), fn(2), fn(3)].map(wrapPromise)
for (let promise of promises) assert(promise.isPending())

await clock.tickAsync(1)
for (let promise of promises) expect(promise.value()).to.equal(6)
expect(foo.args).to.deep.equal([[3]])

promises = [fn(4), fn(-4), fn(5)].map(wrapPromise)
promises.forEach(p => p.catch(() => {}))
await clock.tickAsync(40)
for (let promise of promises) assert(promise.isPending())

await clock.tickAsync(60)
for (let promise of promises) expect(promise.value()).to.equal(10)

expect(foo.args).to.deep.equal([[3], [5]])

await clock.tickAsync(1000)
expect(foo.args).to.deep.equal([[3], [5]])

promises = [fn(1), fn(2), fn(3)].map(wrapPromise)
await clock.tickAsync(1)
for (let promise of promises) expect(promise.value()).to.equal(6)

promises = [fn(-10)].map(wrapPromise)
await clock.tickAsync(100)
assert(promises[0].isRejected())
})
it('works', async function(): Promise<void> {
const foo = sinon.spy(
Expand Down

0 comments on commit ad364ff

Please sign in to comment.