jQuery Deferred,$ .when()和fail()回调参数 [英] jQuery Deferred's, $.when() and the fail() callback arguments

查看:431
本文介绍了jQuery Deferred,$ .when()和fail()回调参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用 $。when()时,当其中一个延期操作未成功时,我收到了意外结果。

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

使用此JavaScript创建了2个延迟。第一个成功,第二个失败。

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

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]));
    });

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

我得到失败! f1,f2:[456 from f2,null]

问题在于 .fail( )回调用 f2()拒绝传递的值,被路由到第一个参数,我期望 f1Value 。这意味着我真的没有办法知道哪个延迟对象实际发布了 reject(),而且我也不知道故障数据实际属于哪个操作。

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()会得到参数 null,'456从f2'开始,因为第一次延期没有失败。或者我只是没有在这里做正确的延迟?

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?

如果回调中的参数顺序如何,我如何知道哪些延迟失败,以及哪些拒绝参数属于哪个延迟失败?不受尊重?

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?

推荐答案

在内部,拒绝和失败路径由两个完全独立的队列处理,因此它只是不按你期望的方式工作。

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

为了知道when()组中哪个原始Deferred失败,你可以让它们自己传递.reject()调用作为对象文字或其他内容的一部分。

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.

这篇关于jQuery Deferred,$ .when()和fail()回调参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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