微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

jQuery.Deferred()然后,如何解决多个参数

所以我的API希望当一个特定的延迟被解决它得到2个参数.
fn().done(function(arg1,arg2) {
  console.log(arg1,arg2);
}).fail(function(err) {
  console.error(err);
});

现在关于上面的fn功能,需要先等待一些其他的延迟返回才能解决.

function other() {
  // stubbed out to always resolve
  return $.Deferred().resolve().promise();
}

function fn() {
  return other().then(function() {
    return [1,2];
  });
}

但是这并不奏效,因为arg1将会出现[1,2],而arg2将会是未定义的.我不知道如何从Deferred.then()第一个成功过滤器函数参数返回一些东西,以便最终的管道延迟解析与多个参数.

当然我可以这样做:

function fn() {
  var done = $.Deferred();
  other().done(function(){
    done.resolve(1,2);
  }).fail(function(){
    done.reject.apply(done,arguments);
  });
  return done.promise();
}

但是这并不像使用.then()那么优雅,我现在每次都需要担心负面的故障情形API,即使我知道我只是通过拒绝的状态来管理.

是的,我也可以改变fn()api来解决一个数组,但我真的希望有一个优雅的解决方案.

解决方法

您必须调用resolve()或reject()才能传递多个参数.

.then()不包含用于“传播”返回的集合的任何机制.它只会将收藏品保持原样作为第一个参数.

但是,它将与退回的递延或承诺进行交互.从paragraph starting with “As of jQuery 1.8

These filter functions can return a new value to be passed along to the promise’s .done() or .fail() callbacks,or they can return another observable object (Deferred,Promise,etc) which will pass its resolved / rejected status and values to the promise’s callbacks.

所以,你可以使用其他()的例子作为fn()的基础来保持它与另一个Deferred()相当简洁:

function fn() {
    return other().then(function () {
        return $.Deferred().resolve(1,2).promise();
    });
}

fn().then(function (a,b) {
    console.log(arguments.length,a,b); // 2 1 2
});

http://jsfiddle.net/cqac2/

原文地址:https://www.jb51.cc/jquery/179288.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐