Javascript jQuery Deferred 的 $.when() 和 fail() 回调参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5518181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:35:06  来源:igfitidea点击:

jQuery Deferred's, $.when() and the fail() callback arguments

javascriptjqueryjquery-deferred

提问by Alex Wayne

I'm getting an unexpected result when using $.when()when one of the deferred operations does not succeed.

$.when()当延迟操作之一未成功时使用时,我得到了意外的结果。

Take this JavaScript, which created 2 deferreds. The first one succeeds and the second one fails.

以这个 JavaScript 为例,它创建了 2 个延迟。第一个成功,第二个失败。

var f1 = function() {
    return $.Deferred(function(dfd) {
        dfd.resolve('123 from f1');
    }).promise();
};

var f2 = function() {
    return $.Deferred(function(dfd) {
        dfd.reject('456 from f2');
    }).promise();
};

$.when(f1(), f2())
    .then(function(f1Val, f2Val) {
        alert('success! f1, f2: ' + JSON.stringify([f1Val, f2Val]));
    })
    .fail(function(f1Val, f2Val) {
        alert('fail!    f1, f2: ' + JSON.stringify([f1Val, f2Val]));
    });

Run it yourself: http://jsfiddle.net/r2d3j/2/

自己运行:http: //jsfiddle.net/r2d3j/2/

I get fail! f1, f2: ["456 from f2", null]

我得到 fail! f1, f2: ["456 from f2", null]

The problem is that in the .fail()callback the value passed with the f2()rejection, is being routed to the first argument, where i expect the f1Value. Which means that I don't really have a way of know which deferred object actually posted that reject(), and I also dont know which operation that failure data actually belongs to.

问题是在.fail()回调中,通过f2()拒绝传递的值被路由到第一个参数,我希望f1Value. 这意味着我真的没有办法知道哪个延迟对象实际发布了那个reject(),我也不知道失败数据实际上属于哪个操作。

I would have expected that .fail()would get arguments null, '456 from f2'since the first deferred did not fail. Or am I just not doing deferreds right way here?

我原以为.fail()这会引起争论,null, '456 from f2'因为第一个 deferred 没有失败。或者我只是在这里没有正确地进行延期?

How do I know which deferreds failed, and which rejection arguments belong to which failed deferred if the argument order in the callback is not respected?

如果不遵守回调中的参数顺序,我如何知道哪些延迟失败,哪些拒绝参数属于哪些失败延迟?

采纳答案by Pointy

Internally, the "reject" and "fail" paths are handled by two totally separate queues, so it just doesn't work the way you expect.

在内部,“拒绝”和“失败”路径由两个完全独立的队列处理,因此它不会以您期望的方式工作。

In order to know which original Deferred failed from the "when()" group, you could have them pass themselves along with the ".reject()" call as part of an object literal or something.

为了知道“when()”组中哪个原始延迟失败,您可以让它们与“.reject()”调用一起作为对象文字或其他东西的一部分传递。

回答by InfinitiesLoop

$.when()will execute the failed callback (2nd parameter passed to then()) immediately if any one of the parameters fails. It's by design. To quote the documentation:

$.when()then()如果任何一个参数失败,将立即执行失败的回调(传递给 的第二个参数)。这是设计使然。引用文档:

http://api.jquery.com/jQuery.when/

http://api.jquery.com/jQuery.when/

In the multiple-Deferreds case where one of the Deferreds is rejected, jQuery.when immediately fires the failCallbacks for its master Deferred. Note that some of the Deferreds may still be unresolved at that point. If you need to perform additional processing for this case, such as canceling any unfinished ajax requests, you can keep references to the underlying jqXHR objects in a closure and inspect/cancel them in the failCallback.

在多个延迟的情况下,其中一个延迟被拒绝,jQuery.when 会立即为其主延迟触发 failCallbacks。请注意,此时某些延迟可能仍未解决。如果您需要针对这种情况执行额外的处理,例如取消任何未完成的 ajax 请求,您可以在闭包中保留对底层 jqXHR 对象的引用,并在 failCallback 中检查/取消它们。

There's actually no built-in way of getting a callback that waits untils all of them are finished regardless of their success/failure status.

实际上没有内置的方法来获取回调,无论它们的成功/失败状态如何,它都会等待所有这些都完成。

So, I built a $.whenAll()for you :)
It always waits until all of them resolve, one way or the other:

因此,我$.whenAll()为您构建了一个:)
它总是等到所有问题都解决后,以一种或另一种方式:

http://jsfiddle.net/InfinitiesLoop/yQsYK/51/

http://jsfiddle.net/InfinitiesLoop/yQsYK/51/

$.whenAll(a, b, c)
    .then( callbackUponAllResolvedOrRejected );

回答by ScottE

I've faced this same problem, and I dealt with it by using the .always callback and inspecting my array of deferred objects. I had an unknown number of ajax calls, so I had to do the following:

我遇到了同样的问题,我通过使用 .always 回调并检查我的延迟对象数组来处理它。我有未知数量的 ajax 调用,所以我必须执行以下操作:

// array of ajax deletes
var deletes = [];
$checkboxes.each(function () {
    deletes.push(deleteFile(this));
});

$.when.apply($, deletes)
  .always(function () {
      // unfortunately .fail shortcircuits and returns the first fail,
      // so we have to loop the deferred objects and see what happened.

      $.each(deletes, function () {
          this.done(function () {
              console.log("done");
          }).fail(function () {
              console.log("fail");
          });
      });
  });

The deleteFile method returns a promise, which has .done or .fail callbacks.

deleteFile 方法返回一个承诺,它具有 .done 或 .fail 回调。

This allows you to take action after all deferreds have completed. In my case I'm going to show a delete file error summary.

这允许您在所有延迟完成后采取行动。就我而言,我将显示删除文件错误摘要。

I just tried this, and unfortunately I had to put a interval timer to check that they were all truly done after my $.each on the deferred objects. This seems odd and counterintuitive.

我刚试过这个,不幸的是我不得不设置一个间隔计时器来检查它们是否在我的 $.each 之后真正完成了延迟对象。这似乎很奇怪且违反直觉。

Still trying to understand these deferreds!

仍在努力理解这些延迟!

回答by Alex Davidson

http://jsfiddle.net/InfinitiesLoop/yQsYK/

http://jsfiddle.net/InfinitiesLoop/yQsYK/

This will always reject if given multiple inputs. rejected = true;should be rejected |= reject;

如果给定多个输入,这将始终拒绝。rejected = true;应该rejected |= reject;