Created
June 22, 2016 16:18
-
-
Save cowboy/167c8b58a6df6c34bec5da0ef8ed3178 to your computer and use it in GitHub Desktop.
javascript / bluebird: promise batch arrays
This file contains hidden or 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
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); |
This file contains hidden or 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
$ 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