Created
August 11, 2016 08:10
-
-
Save stephenwil/5e2f13a5cead3abaf1f0d98a6c5c50e6 to your computer and use it in GitHub Desktop.
Better promise constructs
This file contains hidden or 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 ExampleAPIHandler(downChainResponse, otherdata, next) { | |
var promiseArray = []; | |
var respJSON = { | |
body: {}, | |
success: true, | |
warnings: [], | |
errors: [] | |
}; | |
promiseArray.push(processingStep1(downChainResponse.body.schemes)); | |
promiseArray.push(processingStep2(downChainResponse.body.schemes,userId)); | |
// Need to aggregate the data for the front end. | |
return Promise.all(promiseArray) | |
// Example of Bad | |
.then(function (resultArray) { | |
if (!resultArray || resultArray.length == 0) { | |
throw new Error('Error in executing processSchemesNode and processFileLockedStatus'); | |
} | |
// Aggregate responses - return the updated schemes | |
return aggregateSchemesAndLockStatus(resultArray); | |
}) | |
// Example of better | |
.then(aggregateSchemesAndLockStatus) // Just call a named function and do any checking in that function | |
.catch(handleCatch) | |
} | |
function aggregateSchemesAndLockStatus(resultArray) { | |
// Check here and allow parent catch to catch | |
if (!resultArray || resultArray.length == 0) { | |
throw new Error('Error in aggregating data'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment