Skip to content

Instantly share code, notes, and snippets.

@thehig
Last active October 6, 2016 14:38
Show Gist options
  • Save thehig/e2d40f578dbc61aefce64bd7a89f8124 to your computer and use it in GitHub Desktop.
Save thehig/e2d40f578dbc61aefce64bd7a89f8124 to your computer and use it in GitHub Desktop.
js: Promise Chaining
myModule.validate = function(params){
return new WinJS.Promise(function(ccb, ecb){
myModule.preValidate(params).then(
function prevalidateSuccess(result){
ccb(result);
},
function prevalidateError(err){
ecb(err);
})
});
}
/*
Perform the preValidate
Throw out any preValidate errors
Throw out any validate errors
Only continue if preValidate is successful
*/
myModule.validate = function(params){
return myModule.preValidate(params)
.then(function success(result){
});
}
myModule.validate = function(params){
return myModule.preValidate(params)
.then(function success(result){
}, function error(err){
// Don't do both, do one or the other
return err; // Goes to next 'normal' promise
throw err; // Goes to next 'error' promise
});
}
// Chaining some promises
myModule.validate = function(params){
return myModule.preValidate(params)
.then(function preValidateSuccess(result){
// Return another promise
return doSomethingAsync(result);
})
.then(function successSomethingAsync(something){
// Do something and return
});
}
// Errors are handled at the first available error pipeline
// If the error promise returns, we go to next normal promise
// If the error throws, we go to the next error promise
myModule.validate(null).then(null, function error(err){
// This would be the preValidate error, as this is the first error pipeline
});
// validObject is valid enough to pass preValidate, but internet is down or some other http error
myModule.validate(validObject).then(null, function error(err){
// This would be the validate error if there were no internet connection for example
});
// Workblob example:
// Example promises
var getUserAsync = ()=> return user;
var getAddressAsync = ()=> return address;
var workblob = {}
workblob.inputObject = target
myApp.validate = function(workblob){
return new WinJS.Promise(function(ccb, ecb){
if(!workblob.target) return ecb(new Error("No Workblob target"));
var getAndSavePromise = getUserAsync(workblob.target).then(function(user){
// workblob.response.user = user;
myApp.response.user = user;
return workblob;
});
ccb(getAndSavePromise);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment