@grafana/ui
Version:
Grafana Components Library
1 lines • 2.22 kB
Source Map (JSON)
{"version":3,"file":"useLatestAsyncCall.mjs","sources":["../../../../src/components/Combobox/useLatestAsyncCall.ts"],"sourcesContent":["import { useCallback, useRef } from 'react';\n\ntype AsyncFn<T, V> = (value: T) => Promise<V>;\n\n/**\n * Wraps an async function to ensure that only the latest call is resolved.\n * Used to prevent a faster call being overwritten by an earlier slower call.\n */\nexport function useLatestAsyncCall<T, V>(fn: AsyncFn<T, V>): AsyncFn<T, V> {\n const latestValueCount = useRef<number>(0);\n\n const wrappedFn = useCallback(\n (value: T) => {\n latestValueCount.current++;\n const requestCount = latestValueCount.current;\n\n return new Promise<V>((resolve, reject) => {\n fn(value)\n .then((result) => {\n // Only resolve if the value is still the latest\n if (requestCount === latestValueCount.current) {\n resolve(result);\n } else {\n reject(new StaleResultError());\n }\n })\n .catch(reject);\n });\n },\n [fn]\n );\n\n return wrappedFn;\n}\n\nexport class StaleResultError extends Error {\n constructor() {\n super('This result is stale and is discarded');\n this.name = 'StaleResultError';\n Object.setPrototypeOf(this, new.target.prototype); // Necessary for instanceof to work correctly\n }\n}\n"],"names":[],"mappings":";;;AAQO,SAAS,mBAAyB,EAAA,EAAkC;AACzE,EAAA,MAAM,gBAAA,GAAmB,OAAe,CAAC,CAAA;AAEzC,EAAA,MAAM,SAAA,GAAY,WAAA;AAAA,IAChB,CAAC,KAAA,KAAa;AACZ,MAAA,gBAAA,CAAiB,OAAA,EAAA;AACjB,MAAA,MAAM,eAAe,gBAAA,CAAiB,OAAA;AAEtC,MAAA,OAAO,IAAI,OAAA,CAAW,CAAC,OAAA,EAAS,MAAA,KAAW;AACzC,QAAA,EAAA,CAAG,KAAK,CAAA,CACL,IAAA,CAAK,CAAC,MAAA,KAAW;AAEhB,UAAA,IAAI,YAAA,KAAiB,iBAAiB,OAAA,EAAS;AAC7C,YAAA,OAAA,CAAQ,MAAM,CAAA;AAAA,UAChB,CAAA,MAAO;AACL,YAAA,MAAA,CAAO,IAAI,kBAAkB,CAAA;AAAA,UAC/B;AAAA,QACF,CAAC,CAAA,CACA,KAAA,CAAM,MAAM,CAAA;AAAA,MACjB,CAAC,CAAA;AAAA,IACH,CAAA;AAAA,IACA,CAAC,EAAE;AAAA,GACL;AAEA,EAAA,OAAO,SAAA;AACT;AAEO,MAAM,yBAAyB,KAAA,CAAM;AAAA,EAC1C,WAAA,GAAc;AACZ,IAAA,KAAA,CAAM,uCAAuC,CAAA;AAC7C,IAAA,IAAA,CAAK,IAAA,GAAO,kBAAA;AACZ,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,GAAA,CAAA,MAAA,CAAW,SAAS,CAAA;AAAA,EAClD;AACF;;;;"}