Created
July 15, 2024 04:28
-
-
Save kohki-shikata/8a2e16778ceaa2d7db74bac2fc3688e1 to your computer and use it in GitHub Desktop.
逐次処理をPromise.allで非同期に並列処理したいが、少しだけディレイを入れたい(APIの制限対策など)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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