Created
February 3, 2022 03:59
-
-
Save tecfu/833624fefbf5256c137d5a923a0df06c to your computer and use it in GitHub Desktop.
Javscript execute promises sequentially, subject to delay
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
/** | |
* How to execute a list of functions subject to a delay | |
*/ | |
const interval = 3000 | |
const delay = time => new Promise(resolve => setTimeout(resolve, time)) | |
// in practice, this would be an array of functions with nested callbacks | |
const fns = Array(3).fill((() => console.log(Date.now()))) | |
// wait for each delay before executing the next function | |
async function delayJobs () { | |
var response = [] | |
// works | |
for(var i = 0; i < fns.length; i++) { | |
if(i !== 0) await delay(interval) | |
response.push(fns[i]()) | |
} | |
// works | |
//for(fn of fns) { | |
// await delay(interval) | |
// response.push(fn()) | |
//} | |
// doesn't work, executes in parallel | |
//fns.map( async (fn, i) => { | |
// if(i !== 0) await delay(interval) | |
// response.push(fns[i]()) | |
//}) | |
return response | |
} | |
delayJobs() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment