Skip to content

Instantly share code, notes, and snippets.

@qathom
Last active August 15, 2019 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qathom/acc8995b77cadf83e653155f4543c5b9 to your computer and use it in GitHub Desktop.
Save qathom/acc8995b77cadf83e653155f4543c5b9 to your computer and use it in GitHub Desktop.
Run array stacks in series (create stacks from an array and run them in series) - Async function is supported
const { forEachSeries } = require('p-iteration');
// Async function
function asyncFn(item, time = 1000) {
return new Promise((resolve) => {
setTimeout(() => {
console.log(item);
resolve(item);
}, time);
});
}
// Stack creator
function getStacks(list = [], size = 2) {
const stacks = [];
const { length } = list;
if (length < size) {
return [list];
}
for (let i = 0; i < length; i += size) {
const slice = list.slice(i, i + size);
stacks.push(slice);
}
return stacks;
}
// Demo
(async () => {
console.log('Start');
/*
* Create 5 stacks from the array and run them in series
*/
const collection = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const stackSize = 2;
const listStacks = getStacks(collection, stackSize);
await forEachSeries(listStacks, async (stack, i) => {
const process = stack.map((item) => (asyncFn(item, 2000)));
console.log(`Running stack ${i}`);
await Promise.all(process);
console.log('OK!');
});
console.log('End');
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment