Skip to content

Instantly share code, notes, and snippets.

@assertnotnull
Created October 19, 2022 17:57
Show Gist options
  • Save assertnotnull/87454e0f8374b6472018c89517910a0d to your computer and use it in GitHub Desktop.
Save assertnotnull/87454e0f8374b6472018c89517910a0d to your computer and use it in GitHub Desktop.
mapAsync
import { PerformanceObserver, performance } from 'perf_hooks';
import R from "ramda";
const perfObserver = new PerformanceObserver((items) => {
items.getEntries().forEach((entry) => {
console.log(`${entry.name}: ${entry.duration}}`)
})
})
perfObserver.observe({entryTypes: ["measure"]})
async function mapAsync<Type, ReturnedType>(
promiseFunc: (value: Type) => Promise<ReturnedType>,
values: Type[],
chunk = 3
) {
const processChunk = processWithFunction<Type, ReturnedType>(promiseFunc);
const chunks = R.splitEvery(chunk, values);
return R.flatten(await R.reduce(processChunk, Promise.resolve([]), chunks));
}
function processWithFunction<Type, ReturnedType>(
promiseFunc: (x: Type) => Promise<ReturnedType>
) {
return async (acc: Promise<ReturnedType[]>, chunkOfValues: Type[]) => {
performance.mark('start')
const resolved = await acc;
const outcome = await Promise.all(
chunkOfValues.map((chunk) => promiseFunc(chunk))
);
resolved.push(...outcome);
performance.mark('end')
performance.measure('start-end', 'start', 'end')
console.log({resolved})
return resolved;
};
}
let callCount = 0
async function callDB(val) {
return new Promise((resolve) => {
setTimeout(() => {
// console.log(`calling DB with value: ${val}`);
callCount++
resolve(true);
}, 1000);
});
}
mapAsync(callDB, R.range(0, 6),3).then((resolves) => console.log({resolves,callCount}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment