Skip to content

Instantly share code, notes, and snippets.

@kohki-shikata
Created July 15, 2024 04:28
Show Gist options
  • Save kohki-shikata/8a2e16778ceaa2d7db74bac2fc3688e1 to your computer and use it in GitHub Desktop.
Save kohki-shikata/8a2e16778ceaa2d7db74bac2fc3688e1 to your computer and use it in GitHub Desktop.
逐次処理をPromise.allで非同期に並列処理したいが、少しだけディレイを入れたい(APIの制限対策など)
const delayFunc = (ms: number) =>
new Promise((resolve) => setTimeout(resolve, ms));
const syncronusProcess = async (
flag: string | undefined,
time: number = 1000,
iteration: number = 4,
) => {
let i = 1;
while (i <= iteration) {
await delayFunc(time);
console.log(`${flag}${i} did fire`);
i++;
}
};
const flags = ["A", "B", "C", "D"];
const delayedParallel = async (func: Function, delay: number = 400) => {
let promises = flags.map(async (flag, index: number) => {
await delayFunc(delay * (index + 1)); // 200msの遅延を作成する
try {
if (flag === "B") {
throw new Error("B is error term");
}
await func(flag, 1000, 4);
} catch (error) {
console.error(error);
}
});
// Promise.allで全ての非同期処理が完了するのを待つ
await Promise.all(promises);
console.log("All processes are accomplished.");
};
(async () => await delayedParallel(syncronusProcess, 800))();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment