UNPKG

@grafana/ui

Version:
34 lines (31 loc) 900 B
import { useRef, useCallback } from 'react'; "use strict"; function useLatestAsyncCall(fn) { const latestValueCount = useRef(0); const wrappedFn = useCallback( (value) => { latestValueCount.current++; const requestCount = latestValueCount.current; return new Promise((resolve, reject) => { fn(value).then((result) => { if (requestCount === latestValueCount.current) { resolve(result); } else { reject(new StaleResultError()); } }).catch(reject); }); }, [fn] ); return wrappedFn; } class StaleResultError extends Error { constructor() { super("This result is stale and is discarded"); this.name = "StaleResultError"; Object.setPrototypeOf(this, new.target.prototype); } } export { StaleResultError, useLatestAsyncCall }; //# sourceMappingURL=useLatestAsyncCall.mjs.map