Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sequential promise processing
'use strict';
/**
* Run through promises sequentially. Useful when breaking 1000s records into manageable chunks
*/
function processFile (filename) {
return new Promise((superResolve, superReject) => {
let promises = [];
for (let i = 10; i > 0; i--) {
promises.push(new Promise((resolve, reject) => {
setTimeout(() => {
resolve(10 - i + 1);
}, i * 10);
}));
}
let last = promises.reduce((curr, next) => {
return curr.then(value => {
console.log(next, value);
return next;
});
}, Promise.resolve('First'));
last.then(result => {
superResolve('Totally done');
});
});
}
let filenames = [1, 2, 3, 4, 5, 6];
let last = filenames.reduce((curr, next) => {
return curr.then(result => {
return new Promise((resolve, reject) => {
processFile(next + '.json')
.then(result => {
resolve('Resolved: ' + next + '.json');
})
});
});
}, Promise.resolve('First'));
last
.then(result => {
console.log('Finished! ' + result);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.