Created
August 24, 2016 08:46
-
-
Save roppa/51d713f37448237ec6dc959c5020721d to your computer and use it in GitHub Desktop.
Sequential promise processing
This file contains 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
'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