Function: deferred()
deferred<
T,ThisArg,Delay>(options?):DeferredAsyncCallback
Defined in: packages/promise/src/deferred.ts:87
Function
PromisE.deferred The adaptation of the deferred() function tailored for Promises.
Type Parameters
T
T
ThisArg
ThisArg = unknown
Delay
Delay extends number = number
Parameters
options?
DeferredAsyncOptions<ThisArg, Delay>
(optional) options
Returns
a callback that is invoked in one of the followin 3 methods:
- sequential: when
delayMs <= 0ordelayMs = undefined - debounced: when
delayMs > 0andthrottle = false - throttled: when
delayMs > 0andthrottle = true
The main difference is that:
Notes:
- A "request" simply means invokation of the returned callback function
- By "handled" it means a "request" will be resolved or rejected.
PromisE.deferredis to be used with promises/functionsThere is no specific time delay.
The time when a request is completed is irrelevant.
If not throttled:
- Once a request is handled, all previous requests will be ignored and pool starts anew.
- If a function is provided in the returned callback, ALL of them will be invoked, regardless of pool size.
- The last/only request in an on-going requests' pool will handled (resolve/reject).
If throttled:
- Once a requst starts executing, subsequent requests will be added to a queue.
- The last/only item in the queue will be handled. Rest will be ignored.
- If a function is provided in the returned callback, it will be invoked only if the request is handled. Thus, improving performance by avoiding unnecessary invokations.
- If every single request/function needs to be invoked, avoid using throttle.
If throttled and
strictis truthy, all subsequent request while a request is being handled will be ignored.
Example
typescript
const example = throttle => {
const df = PromisE.deferred(throttle)
df(() => PromisE.delay(5000)).then(console.log)
df(() => PromisE.delay(500)).then(console.log)
df(() => PromisE.delay(1000)).then(console.log)
// delay 2 seconds and invoke df() again
setTimeout(() => {
df(() => PromisE.delay(200)).then(console.log)
}, 2000)
}
// Without throttle
example(false)
// `1000` and `200` will be printed in the console
// with throttle
example(true)
// `5000` and `200` will be printed in the console
// with throttle with strict mode
example(true)
// `5000` will be printed in the console