Skip to content

Instantly share code, notes, and snippets.

@dimied
Forked from nelsongomes/modified-costly-call.ts
Created July 13, 2023 14:15
Show Gist options
  • Save dimied/35a7aa754bb3cdc47f5d47359a21d3f2 to your computer and use it in GitHub Desktop.
Save dimied/35a7aa754bb3cdc47f5d47359a21d3f2 to your computer and use it in GitHub Desktop.
import { delay } from 'ts-timeframe';
import { OperationRegistry } from 'reliable-caching';
const operationRegistry = new OperationRegistry('costlyFunction');
async function simulatedCall(a: number, b: number) {
// these 3 lines represent our call
await delay(200);
console.log(`calculated ${a} * ${b}`);
return a * b;
}
async function costlyFunction(a: number, b: number): Promise<number> {
const uniqueOperationKey = `${a}:${b}`;
const promiseForResult = operationRegistry.isExecuting<number>(uniqueOperationKey);
// a promise means execution for the same key is ongoing, we just need to await for it
if (promiseForResult) {
return promiseForResult;
}
try {
// otherwise we call it
const value = await simulatedCall(a, b);
// pass value to awaiting promises (in next event loop, to avoid delaying current execution)
operationRegistry.triggerAwaitingResolves(uniqueOperationKey, value);
// return value to current execution
return value;
} catch (e) {
// pass error to awaiting rejects (in next event loop, to avoid delaying current execution)
operationRegistry.triggerAwaitingRejects(uniqueOperationKey, e);
// throw exception to current execution
throw e;
}
}
async function main() {
const values = await Promise.all([
costlyFunction(4, 5),
costlyFunction(4, 5),
costlyFunction(4, 5),
costlyFunction(50, 2),
costlyFunction(50, 2),
costlyFunction(50, 2),
]);
console.log(values);
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment