async-wrappers
Version:
A set of wrapper functions to perform debouncing, throttling, retrying etc.
56 lines (49 loc) • 1.45 kB
JavaScript
import pending from './pending';
import deferred from './deferred';
/**
* A callback that will return a value after [[wait]] is completed.
*
* @typeparam T the type of the value.
*
* @category Wait
*/
/**
* Resolves after a given delay, optionally with a value.
*
* If the delay is `0` the promises will resolve after the current
* runtime event loop.
*
* @param delay The time in milliseconds before the value is returned.
* @param func A function or value that will be returned after waiting.
*
* @returns A promise that resolves with the value/function result.
* The promise has 2 extra functions defined:
* - `cancel` cancels the result and rejects the promise.
* - `stop` stops waiting and resolves the promised value.
*
* @category Wrapper
*/
var wait = (delay, func) => {
var result = pending();
var execute = deferred(() => {
// Typescript doesn't accept the function type guard here
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore
result.complete(typeof func === 'function' ? func() : func);
});
execute.defer(delay);
var promise = result.promise;
promise.cancel = error => {
execute.cancel();
result.error(error ? error : new Error('Cancelled'));
};
promise.stop = () => {
// execute has already finished
if (execute.delay < 0) {
return;
} // call right away
execute.defer(0);
};
return promise;
};
export default wait;