处理 ajax 响应数组的正确方法是什么?我的意思是,由于它是一系列 promise ,当其中一个 ajax 调用失败时会发生什么?
$.when.apply($, array_of_promises).then(
successCallback function(){
// Loop over the arguments to control errors??
},
failCallback function(){
}
);
我在哪里可以检测到错误?我可以在“错误处理函数”中得到它吗?我是否必须检查参数变量上的“成功函数”循环以检查所有 ajax 调用是否已成功完成?
最佳答案
$.when.apply(array_of_promises)
请注意 apply
的第一个参数此处缺少,请传递 $
或 null
。
what happens when one of those ajax calls fail?
In the case where multiple Deferred objects are passed to jQuery.when, the method returns the Promise from a new "master" Deferred object that tracks the aggregate state of all the Deferreds it has been passed. The method will resolve its master Deferred as soon as all the Deferreds resolve, or reject the master Deferred as soon as one of the Deferreds is rejected. If the master Deferred is resolved, it is passed the resolved values of all the Deferreds that were passed to jQuery.when. For example, when the Deferreds are jQuery.ajax() requests, the arguments will be the jqXHR objects for the requests, in the order they were given in the argument list.
In the multiple-Deferreds case where one of the Deferreds is rejected, jQuery.when immediately fires the failCallbacks for its master Deferred. Note that some of the Deferreds may still be unresolved at that point. If you need to perform additional processing for this case, such as canceling any unfinished ajax requests, you can keep references to the underlying jqXHR objects in a closure and inspect/cancel them in the failCallback.
Where would I be able to detect the error? Do I get it in the 'error handling function'?
是的。
Do I have to check in the 'success function' looping over the argument variable for checking that all the ajax calls were successfully done?
没有。如果调用了错误处理程序,则不会调用成功函数。仅当没有错误时才会调用 success 函数。
关于Javascript - 错误处理 - Promise 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20903769/