@grafana/ui
Version:
Grafana Components Library
1 lines • 2.19 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,EAAkC,EAAA;AACzE,EAAM,MAAA,gBAAA,GAAmB,OAAe,CAAC,CAAA;AAEzC,EAAA,MAAM,SAAY,GAAA,WAAA;AAAA,IAChB,CAAC,KAAa,KAAA;AACZ,MAAiB,gBAAA,CAAA,OAAA,EAAA;AACjB,MAAA,MAAM,eAAe,gBAAiB,CAAA,OAAA;AAEtC,MAAA,OAAO,IAAI,OAAA,CAAW,CAAC,OAAA,EAAS,MAAW,KAAA;AACzC,QAAA,EAAA,CAAG,KAAK,CAAA,CACL,IAAK,CAAA,CAAC,MAAW,KAAA;AAEhB,UAAI,IAAA,YAAA,KAAiB,iBAAiB,OAAS,EAAA;AAC7C,YAAA,OAAA,CAAQ,MAAM,CAAA;AAAA,WACT,MAAA;AACL,YAAO,MAAA,CAAA,IAAI,kBAAkB,CAAA;AAAA;AAC/B,SACD,CACA,CAAA,KAAA,CAAM,MAAM,CAAA;AAAA,OAChB,CAAA;AAAA,KACH;AAAA,IACA,CAAC,EAAE;AAAA,GACL;AAEA,EAAO,OAAA,SAAA;AACT;AAEO,MAAM,yBAAyB,KAAM,CAAA;AAAA,EAC1C,WAAc,GAAA;AACZ,IAAA,KAAA,CAAM,uCAAuC,CAAA;AAC7C,IAAA,IAAA,CAAK,IAAO,GAAA,kBAAA;AACZ,IAAO,MAAA,CAAA,cAAA,CAAe,IAAM,EAAA,GAAA,CAAA,MAAA,CAAW,SAAS,CAAA;AAAA;AAEpD;;;;"}