Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@cowboy
Created June 22, 2016 16:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cowboy/167c8b58a6df6c34bec5da0ef8ed3178 to your computer and use it in GitHub Desktop.
Save cowboy/167c8b58a6df6c34bec5da0ef8ed3178 to your computer and use it in GitHub Desktop.
javascript / bluebird: promise batch arrays
import Promise from 'bluebird';
function getBatches(arr, length) {
let i = 0;
const result = [];
while (i < arr.length) {
result.push(arr.slice(i, i + length));
i += length;
}
return result;
}
function getItems() {
const arr = '12345678'.split('');
return Promise.resolve(arr);
}
// All in order
function a() {
return getItems()
.then(items => {
console.log('---');
items.map(item => console.log('a', item));
});
}
// Batched
function b() {
return getItems()
.then(items => getBatches(items, 3))
.mapSeries(items => {
console.log('---');
items.map(item => console.log('b', item));
});
}
a().then(b);
$ babel-node promise-batch-arrays.js
---
a 1
a 2
a 3
a 4
a 5
a 6
a 7
a 8
---
b 1
b 2
b 3
---
b 4
b 5
b 6
---
b 7
b 8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment