-
-
Save commanda/0d3f4c0044443fdce2abca6341bb811a to your computer and use it in GitHub Desktop.
Sequential execution of Promises using reduce()
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
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