【问题标题】:parse.com promises - do i need to have an "error" function in each "then"?parse.com 承诺 - 我需要在每个“then”中都有一个“error”函数吗?
【发布时间】:2014-04-01 13:29:15
【问题描述】:

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

我有这样一个云代码功能,它可以做多种事情 - 例如,检查用户是否存在,如果用户存在,则将一些数据保存在不同的表中,然后更新用户表以引用这个新表 - 所以我会有一个 parse.Query 来检查用户是否存在,然后有几个 then 语句在另一个表上运行更新并让用户表引用这个新行。

在这种情况下,我是打算有 几个 错误函数(例如,每个 parse.Query 一个),还是可以接受 一个 错误函数在最后一个then 承诺?

【问题讨论】:

标签: javascript parse-platform promise


【解决方案1】:

是的。它是可以接受的。

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

try{
    first();
} catch(e) {
    //handle
}
try{
    second();
} catch(e) {
    //handle
}
try{
    third();
} catch(e) {
    //handle
}

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

try {
   first();
   second();
   third();
} catch (e) {
    // handle error in whole flow.
}

同样的承诺:

 first().then(second).then(third).catch(function(e){ /* handle error */});

或者,像Parse.Promise这样没有捕获的实现:

 first().then(second).then(third).then(null,function(e){ /* handle error */ });

控制流程与您所期望的完全一样 - 如果 first 失败,那么它将由 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");
});

在考虑 Promise 的行为方式时,请始终考虑同步类比。

【讨论】:

  • 显然 jQuery(以及 Parse)promise 错误不会由错误函数处理,除非它返回一个 promise。也就是说,最后一个警报实际上不会触发!我已经用 Parse Cloud Code 对此进行了测试。
  • @DmitriZaitsev 如果我可以建议,请使用一个体面的承诺实现。添加 Bluebird,您所要做的就是 Promise.cast(或事件只是 Promise.resolve)您的承诺,这将使它们受到信任 Bluebird 承诺为您提供更丰富、更快和更可调试的 API。
  • 不幸的是,我对 Parse Cloud Code 的控制有限。但是,使用他们当前的 promise API,我只需要记住在每个回调中返回一个 promise。
  • 这里是Parse的详细解释:blog.parse.com/2013/01/29/…
  • 关于使用 Bluebird 或其他外部库 - 我需要看到真正的回报。开箱即用的 Parse 实现无法轻松实现。
猜你喜欢
  • 2019-09-28
  • 2015-01-14
  • 2012-09-02
  • 2020-05-12
  • 1970-01-01
  • 1970-01-01
  • 2013-08-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多