Skip to content

Instantly share code, notes, and snippets.

@sramam
Created March 17, 2018 00:48
Show Gist options
  • Save sramam/ccd2f221a12b55a38e4fe47a40ccc7fc to your computer and use it in GitHub Desktop.
Save sramam/ccd2f221a12b55a38e4fe47a40ccc7fc to your computer and use it in GitHub Desktop.
Map & Reduce promises with concurrency throttling - an example
const pReduce = require('p-reduce');
const pMap = require('p-map');
const delay = require('delay');
// const batches = [['a'], ['b', 'c'], ['d', 'e', 'f', 'g'], ['h'], ['i'], ['j', 'k']];
const batches = [['a', 'b', 'c', 'd', 'e', 'f', 'g'], ['h'], ['i'], ['j', 'k']];
const step = 2000;
const max = 5000;
const start = Date.now();
const concurrency = 3;
pReduce(batches, async (sum0, batch) => {
console.log(`------ ${Date.now()- start}`);
const result = await pMap(batch, async child => {
const t = step + Math.random() * max;
console.log(`processing '${child}' ${t} ${Date.now()- start}`);
await delay(t);
console.log(`completed '${child}'`);
return child;
}, { concurrency });
return result.reduce((sum1, r) => {
return sum1 = `${sum1}${r},`;
}, sum0);
}, '>>').then(result => console.log(result)).catch(err => console.log(`ERROR: ${err}`));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment