Skip to content

Instantly share code, notes, and snippets.

@roppa
Created August 24, 2016 08:46
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 roppa/51d713f37448237ec6dc959c5020721d to your computer and use it in GitHub Desktop.
Save roppa/51d713f37448237ec6dc959c5020721d to your computer and use it in GitHub Desktop.
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