Skip to content

Instantly share code, notes, and snippets.

@commanda
Forked from anvk/promises_reduce.js
Last active September 6, 2016 21:50
Show Gist options
  • Save commanda/0d3f4c0044443fdce2abca6341bb811a to your computer and use it in GitHub Desktop.
Save commanda/0d3f4c0044443fdce2abca6341bb811a to your computer and use it in GitHub Desktop.
Sequential execution of Promises using reduce()
function createPromiseForFunction(e, functionThatTakesOneItem)
{
return new Promise((resolve, reject) => {
resolve(functionThatTakesOneItem(e));
});
}
function performSequentially(arr, functionThatTakesOneItem)
{
var finalResult = [];
return new Promise(function(resolve, reject){
resolve(arr.reduce((promise, item) => {
return promise
.then((result) => {
console.log('item '+item);
return createPromiseForFunction(item, functionThatTakesOneItem)
.then(result => finalResult.push(result));
})
.catch(function(reason)
{
console.error('reason: '+reason);
return Promise.reject(reason);
});
}, Promise.resolve()));
})
.then(function(){
return Promise.resolve(finalResult);
});
}
function tryOut()
{
var values = [];
for(var i = 0; i < 4; i++)
{
values.push(i);
}
var processFile = function(filename)
{
console.log('processing '+filename);
return new Promise(function(resolve, reject){
var product = filename + '/differented.png';
setTimeout(() => resolve(product), 200);
});
}
performSequentially(values, processFile)
.then(function(result){
console.log('final result is: '+result);
return Promise.resolve('hey '+result.join('\n'));
})
.catch(function(reason){
console.error('blah '+reason.stack);
});
}
if(require.main === module)
{
tryOut();
}
exports.performSequentially = performSequentially;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment