sb-mig
Version:
CLI to rule the world. (and handle stuff related to Storyblok CMS)
30 lines (29 loc) • 909 B
JavaScript
/**
* Async utility functions
*/
/**
* Delay execution for a specified time
*
* @param time - Time to delay in milliseconds
* @returns Promise that resolves after the delay
*
* @example
* await delay(1000); // Wait 1 second
*/
export const delay = (time) => new Promise((resolve) => setTimeout(resolve, time));
export const mapWithConcurrency = async (items, concurrency, mapper) => {
if (items.length === 0) {
return [];
}
const limit = Math.max(1, Math.floor(concurrency));
const results = new Array(items.length);
let nextIndex = 0;
const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
while (nextIndex < items.length) {
const currentIndex = nextIndex++;
results[currentIndex] = await mapper(items[currentIndex], currentIndex);
}
});
await Promise.all(workers);
return results;
};