Skip to content

Instantly share code, notes, and snippets.

@andrewmacheret
Created October 21, 2019 22:32
Show Gist options
  • Select an option

  • Save andrewmacheret/6ca5ffbffe43e8490bc80fb94046bfd0 to your computer and use it in GitHub Desktop.

Select an option

Save andrewmacheret/6ca5ffbffe43e8490bc80fb94046bfd0 to your computer and use it in GitHub Desktop.
cache of an async function
const resultMap: Map<string, any> = new Map();
const loadData = async (loader: Function, ...args: any) => {
// is there a better way...
const key = JSON.stringify(args);
if (resultMap.has(key)) {
const val = resultMap.get(key);
if (val.state === 'loading') {
return await val.promise();
} else if (val.state === 'failed') {
throw val.error;
} else {
return val.result;
}
}
const resolves: Function[] = [];
const rejects: Function[] = [];
const promise = () => {
return new Promise((resolve, reject) => {
resolves.push(resolve);
rejects.push(resolve);
});
}
resultMap.set(key, {state: 'loading', promise});
try {
const result = await loader(...args);
resultMap.set(key, {state: 'loaded', result});
resolves.forEach(resolve => resolve(result));
return result;
} catch(error) {
resultMap.set(key, {state: 'failed', error});
rejects.forEach(reject => reject(error));
throw error;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment