سؤال

I'm using an array of deferred objects. This array is vble in size so it can have one or more deferred objects. The problem arises when the ajax call is processed. The code is like follow:

$.when.apply($, array_ajax_calls).then(...)

When using .when with .apply, IF the array has just one promise object then the response is an array with three objects:

 // Return the object, the status and the jqXHR object
[Array[1] , "success",  Object ]

If the array contains more than one object then it returns an array of responses like the previous one.

[
    [Array[1] , "success",  Object ],
    [Array[1] , "success",  Object ],
    ...
]

As you see, the response is different. The first one returns an array with three values. The second one returns an array of arrays that contain three values. This makes me have to check if the ajax call was done for one or more objects and change the logic since the response has a different format.

I dont see why I should get a different response. If I passed an array of promises(even if there is just one promise) to the .apply(...) function I would be expecting to get:

[ [Array[1] , "success",  Object ] ]

instead of

[Array[1] , "success",  Object ]

Is there any way to get the same response format?

هل كانت مفيدة؟

المحلول

The behavior you mention in your question is by design, and is due to $.when() only creating its own master promise when it receives more than one argument.

Non-deferred arguments, however, are considered as resolved promises returning these arguments. Therefore, you can systematically pass null as an extra argument to $.when(), like for instance:

$.when.apply($, [null].concat(array_ajax_calls)).then(...)

If you do that, the response in your then() callback will always be of the form:

[
    null,
    [Array[1] , "success",  Object],
    ...
]

From there, you only would have to ignore the first element and process all the others.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top