Created
October 24, 2016 13:32
-
-
Save zahid/b6e06c5e2c262905f61244ce008016da to your computer and use it in GitHub Desktop.
So a list of things walk into a bar . . .
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
// TODO: turn this into a "three guys walk into a bar" joke.... | |
/* | |
You have a list of things you need process, items. In our case, times in seconds. | |
Use "processItemAsynchronously(timeInMilliseconds)" on each item in "items", while processing the items one at a time. | |
Each item completes in random time, asynchronously. | |
The question is how to do a list of asynchronous things, one at a time, waiting for the current item to finish before starting the next. | |
*/ | |
const items = [100, 300, 400, 500, 600, 100, 300, 600, 200, 300, 400]; | |
const processItemAsynchronously = (timeInMilliseconds) => { | |
return new Promise((resolve) => { | |
console.log('starting %s', timeInMilliseconds) | |
setTimeout(() => { | |
resolve('Done after ' + timeInMilliseconds + 'ms'); | |
}, timeInMilliseconds); | |
}); | |
}; | |
const processList = (action, items) => { | |
if (items.length > 0) { | |
action(items[0]) | |
.then((message) => { | |
console.log(message); | |
processList(action, items.slice(1, items.length)); | |
}) | |
} | |
} | |
// Do not wait for current item to complete before starting the next one | |
//items.forEach((item) => processItemAsynchronously(item).then((message) => console.log(message))) | |
// Wait for current item to complete before starting the next one | |
//processList(processItemAsynchronously, items); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment