Skip to content

Instantly share code, notes, and snippets.

@FrankV01
Last active July 6, 2017 19:24
Show Gist options
  • Save FrankV01/4be0f1414c3cd05de059f83a3b7163a4 to your computer and use it in GitHub Desktop.
Save FrankV01/4be0f1414c3cd05de059f83a3b7163a4 to your computer and use it in GitHub Desktop.
Convert tOSU-callback-hell.js to promise for article on http://theopensourceu.org/concepts-to-implementations-promise/
//
// require statements omitted for readability and brevity.
var readFile = Promise.promisify(require("fs").readFile); //See http://bluebirdjs.com/docs/api/promise.promisify.html
function processData( startData ) {
//Return a promise which impl will use "then" to implement what was "cbResult"
return new Promise( function(resolve) {
//
// Do something with startingData and ultimatly set result to finalizedResult.
// ...
var finalizedResult = startingData;
return finalizedResult; //Returning something makes it available in chained 'then' statements.
} );
}
function parentMethod() {
readFile('/my/made/up/file.txt')
.then(function callback1(data) { //Note that (data) => {} is a newer way of defining a function in JS.
return processData( data ); //Not available everywhere yet though. Equiv. to function(data) {}
})
.then(function callback2(results) {
return sendResultsToServer(result);
})
.then(function callback3(response) {
executionOrderIsClearer(); //as well as where each method starts and ends.
})
.catch(function(err) {
// Handle errors from the readFile to callback3.
// Like wraping the above in a try/catch
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment