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/

相关文章

1.第一步 设置响应头 header('Access-Control-Allow...
$.inArray()方法介绍 $.inArray()函数用于在数组中搜索指定的...
jquery.serializejson.min.js的妙用 关于这个jquery.seriali...
JS 将form表单数据快速转化为object对象(json对象) jaymou...
jQuery插件之jquery.spinner数字智能增减插件 参考地址:http...