【问题标题】:Preserving arguments when returning data from deferred.then()从 deferred.then() 返回数据时保留参数
【发布时间】:2015-05-25 00:12:55
【问题描述】:

deferred.then 回调中返回数据时如何传递多个参数?

var data = {
    json: JSON.stringify({
        text: 'some text',
        array: [1, 2, 'three'],
        object: {
            par1: 'another text',
            par2: [3, 2, 'one'],
            par3: {}
        }
    }),
    delay: 3
};

$.ajax({
    url:'/echo/json/',
    data: data,
    type: 'POST'
}).then(function(response, statusText, jqXhr){
    response.text = 'foo';
    // how to return the rest of the arguments correctly?
    return response;
}).done(function(response, statusText, jqXhr){
    console.log(response); // <- altered response
    console.log(statusText); // <- how to pass it along?
    console.log(jqXhr); // <- how to pass it along?
});

http://jsfiddle.net/rv1aydvb/

【问题讨论】:

  • 不返回更改后的数据,而是直接调用 next 函数,并使用修改后的参数。
  • @Barmar 返回一个对象仍然会使done 回调中的参数 2 和参数 3 未定义,对吗?我想知道是否有办法在then 回调中设置它们

标签: javascript jquery promise


【解决方案1】:

您需要返回一个deferred,该deferred 使用resolveWith method 解析为多个值。当然,返回单个(但复合)值通常更简洁。

$.ajax(…).then(function(response) {
    response.text = 'foo';
    return $.Deferred().resolveWith(this, arguments); // if you don't replace but modify vals
    // alternatively,  .resolveWith(this, [response, …]);
}).done(function(response, statusText, jqXhr) {…});

【讨论】:

  • 谢谢,我同意这看起来有点乱。我只是出于好奇而问
【解决方案2】:

返回一个包含 statusText 和 jqXhr 的对象。然后您可以将它们作为响应对象的一部分进行访问。像这样

$.ajax({
    url:'/echo/json/',
    data: data,
    type: 'POST'
}).then(function(response, statusText, jqXhr){
    response.text = 'foo';
    return {
        response: response,
        status: statusText,
        jq: jqXhr
    }
}).done(function(response, statusText, jqXhr){
    console.log(response); // <- altered response
    console.log(response.status); // <- undefined
    console.log(response.jq); // <- undefined

});

https://jsfiddle.net/rv1aydvb/3/

【讨论】:

  • 我知道这是可能的。我在问是否有办法定义除第一个参数之外的任何参数。
  • 你可以返回一个数组而不仅仅是一个对象。
  • 不过,它最终会作为第一个参数
  • 是的,但.done 没有statusTextjqXhr。它们是在 .then 中处理的 ajax 调用的一部分
  • 是否有特定原因需要将它们作为单独的参数访问?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-31
  • 2018-01-08
  • 2018-09-03
  • 2018-09-29
相关资源
最近更新 更多