Combining deferred responses [duplicate]

2019-03-05 17:41发布

问题:

This question already has an answer here:

  • AJAX Promises using Array 1 answer

Is it possible, when using jQuery Deferred's $.when to combine the responses into an array?

var promise = $.when(
    ajaxRequest1,
    ajaxRequest2
);

promise.done(callback);

The "callback" function looks like function callback(resp, options). Note how it only accepts a single response.

I thought the following might work, but did not.

var promise = $.when(
    ajaxRequest1,
    ajaxRequest2
);
promise.then(function(resp1, resp2) {
    return [resp1, resp2];
});

回答1:

The problem is that jQuery resolves its ajax promises with 3 arguments, which then become an array of values when you are using $.when on multiple promises. To get only the data (the first argument of each ajax callback), use

var promise = $.when(
    ajaxRequest1,
    ajaxRequest2
).then(function(resp1, resp2) {
    return [resp1[0], resp2[0]];
});