Skip to content

Instantly share code, notes, and snippets.

@zahid
Created October 24, 2016 13:32
Show Gist options
  • Save zahid/ee6998c152d3da6c185f3f100cc5be3d to your computer and use it in GitHub Desktop.
Save zahid/ee6998c152d3da6c185f3f100cc5be3d to your computer and use it in GitHub Desktop.
So a list of things walk into a bar . . .
// 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