Path: blob/main/core/kernel/src/wasm/reuseInFlight.js
1067 views
/* This is from the ISC licensed async-await-utils project, from here:1https://github.com/masotime/async-await-utils/blob/master/src/hof/reuseInFlight.js2Including that quite heavy (due to babel dep) project just for this one function3is a bit much, so I copy/pasted it here.4*/56const DEFAULT_CONFIG = {7createKey(args) {8return JSON.stringify(args);9},10ignoreSingleUndefined: false,11};1213// for a given Promise-generating function, track each execution by the stringified14// arguments. if the function is called again with the same arguments, then instead15// of generating a new promise, an existing in-flight promise is used instead. This16// prevents unnecessary repetition of async function calls while the same function17// is still in flight.18export default function reuseInFlight(asyncFn, config) {19config = {20...DEFAULT_CONFIG,21...(config || {}),22};2324const inflight = {};2526return function debounced(...args) {27if (28config.ignoreSingleUndefined &&29args.length === 1 &&30args[0] === undefined31) {32console.warn("Ignoring single undefined arg (reuseInFlight)");33args = [];34}3536const key = config.createKey(args);37if (!inflight.hasOwnProperty(key)) {38// WE DO NOT AWAIT, we are storing the promise itself39inflight[key] = asyncFn.apply(this, args).then(40(results) => {41// self invalidate42delete inflight[key];43return results;44},45(err) => {46// still self-invalidate, then rethrow47delete inflight[key];48throw err;49}50);51}5253return inflight[key];54};55}565758