parse.com承诺 - 我需要在每个"那么"中有一个"错误"功能吗?

bha*_*ral 1 javascript promise parse-platform

parse.com提供了一个云代码部分,以便我可以编写javascript代码来修改我的parse.com数据库.

我有这样一个云代码函数,可以执行多项操作 - 例如,检查用户是否存在,以及用户是否存在将某些数据保存在不同的表中,然后更新用户表以引用此新表 - 所以我将有一个解析.Query检查用户是否存在,然后是几个then语句在另一个表上运行更新并获取用户表来引用这个新行.

在这种情况下,我的意思是有几个错误函数(例如每个parse.Query一个),或者在最后一个承诺中有一个错误函数是否可以接受then

Ben*_*aum 6

是.它是可以接受的.

Promise就像异常一样,每个都有一个错误函数.then就像.catch每个语句都有一个块:

try{
    first();
} catch(e) {
    //handle
}
try{
    second();
} catch(e) {
    //handle
}
try{
    third();
} catch(e) {
    //handle
}
Run Code Online (Sandbox Code Playgroud)

通常,一次捕获更自然,更清晰

try {
   first();
   second();
   third();
} catch (e) {
    // handle error in whole flow.
}
Run Code Online (Sandbox Code Playgroud)

同样承诺:

 first().then(second).then(third).catch(function(e){ /* handle error */});
Run Code Online (Sandbox Code Playgroud)

或者,没有捕获的实现,如Parse.Promise:

 first().then(second).then(third).then(null,function(e){ /* handle error */ });
Run Code Online (Sandbox Code Playgroud)

控制流程将与您期望的完全一样 - 如果first失败,则它将由第一个错误处理程序处理,并且它将不会执行并在该过程中执行回调,因此:

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");
});
Run Code Online (Sandbox Code Playgroud)

在考虑承诺如何表现时,始终要考虑同步模拟.