我何时应该拒绝承诺? [英] When should I reject a promise?

查看:101
本文介绍了我何时应该拒绝承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一些使用promises的JS代码。例如,我打开一个表单弹出窗口,然后返回 jQuery Deferred 对象。它的工作原理如下:

I'm writing some JS code that uses promises. For example, I open a form pop-up and I return a jQuery Deferred object. It works like this:


  • 如果用户在表单上单击确定并验证,则延迟将解析为表示的对象表单数据。

  • If the user clicks OK on the form, and it validates, the Deferred resolves to an object representing the form data.

如果用户单击取消,则延迟解析为空。

If the user clicks Cancel, then the Deferred resolves to a null.

我想要决定的是Deferred应该拒绝而不是解决?更一般地说,我想知道我何时应该解决类似null对象的问题,什么时候应该拒绝?

What I'm trying to decide is should the Deferred instead reject, instead of resolve? More generally, I'm wondering when should I resolve to something like a null object, and when should I reject?

这里有一些代码展示了两个位置:

Here's some code demonstrating the two positions:

// Resolve with null.
var promise = form.open()
    .done(function (result) {
        if (result) {
            // Do something with result.
        } else {
            // Log lack of result.
        }
    });

// Reject.
var promise = form.open()
    .done(function (result) {            
        // Do something with result.            
    })
    .fail(function () {
        // Log lack of result.
    });


推荐答案

两种策略的语义并不完全相同。明确拒绝延迟是有意义的。

The semantics of your two strategies are not really the same. Explicitly rejecting a deferred is meaningful.

例如, $。when()只要传递的延迟对象成功,就会继续累积结果,但会在第一个失败的对象中挽救。

For instance, $.when() will keep accumulating results as long as the deferred objects it is passed succeed, but will bail out at the first one which fails.

这意味着,如果我们分别重命名你的两个承诺 promise1 promise2

It means that, if we rename your two promises promise1 and promise2 respectively:

$.when(promise1, promise2).then(function() {
    // Success...
}, function() {
    // Failure...
});

上面的代码将等到第二个表单关闭,即使第一个表单被取消,之前调用传递给 then()的一个回调。调用的回调(成功或失败)仅取决于第二种形式的结果。

The code above will wait until the second form is closed, even if the first form is canceled, before invoking one of the callbacks passed to then(). The invoked callback (success or failure) will only depend on the result of the second form.

然而,该代码将不会等待如果第二个表单被取消,则在调用失败回调之前关闭第一个表单。

However, that code will not wait for the first form to be closed before invoking the failure callback if the second form is canceled.

这篇关于我何时应该拒绝承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆