Reputation: 16164
parse.com offers a cloud-code section so that I can write javascript code to modify my parse.com database.
I have such a cloud code function that does multiple things - say, checks if a user exists, and if the user exists saves some data in a different table and then updates the user table to reference this new table - so I would have one parse.Query that checks if the user exists, and then several then
statements to run the update on the other table and get the user table to reference this new row.
In this scenario, am I meant to have several error functions (eg one for each parse.Query), or is it acceptable to have one error function in the very last then
promise?
Upvotes: 1
Views: 1086
Reputation: 276286
Yes. It is acceptable.
Promises are like exceptions, having an error function for each .then
is like having a .catch
block for each statement:
try{
first();
} catch(e) {
//handle
}
try{
second();
} catch(e) {
//handle
}
try{
third();
} catch(e) {
//handle
}
Often, having one catch is more natural and clearer
try {
first();
second();
third();
} catch (e) {
// handle error in whole flow.
}
Likewise with promises:
first().then(second).then(third).catch(function(e){ /* handle error */});
Or, with implementations without catch like Parse.Promise
:
first().then(second).then(third).then(null,function(e){ /* handle error */ });
The flow of control would be exactly like you would expect - if first
fails, then it'll be handled by the first error handler, and it will not execute and fulfillment callbacks in the process so:
Parse.promise.as(true).then(function(){
throw new Error("Promises are throw safe and throws are rejections! funstuff");
}).then(function(){
alert("This will never show");
}).then(function(){
alert("This will never show either");
}).then(null,function(e){
alert("This is the error handler!" + e.message);
}).then(function(){
alert("Since the error was handled this will show");
});
Always think about the synchronous analogue when considering how promises might behave.
Upvotes: 6