如何查找在并行ajax调用期间导致错误的方法

how to find which method is causing the error during parallel ajax call

本文关键字:错误 方法 调用 ajax 何查找 查找 并行      更新时间:2023-09-26

我使用$。当对webapi控制器进行并行ajax调用时,它工作得很好。结构如下:

$.when(GetDataFromMethodA(),GetDataFromMethodB(),GetDataFromMethodC())
 .done(function (responseFromMethodA,responseFromMethodB, responseFromMethodC) {         
               if (responseFromMethodA != null) {
                   //do some action
               }
               if (responseFromMethodB != null) {
                   //do some action
               }
              if (responseFromMethodC != null) {
                   //do some action
               }
            }).fail(function (xhr, textStatus, errorThrown) {               
              //which method raised the exception?
            });

方法:

function GetDataFromMethodA() {
    var Request = {};
    Request.Code = name.find(':selected').val();
    return $.ajax({
        url: 'api/Data/GetCurrentView',
        type: 'POST',
        dataType: 'json',
        data: Request
    });
}

同样,我有方法B和c。

问题:

在某些情况下,任何一个方法都失败了,根据失败的方法,我需要向用户显示适当的消息。当任何一个方法失败时,异常就会在'fail'部分被捕获。但是,如何找到引发异常的方法?

如果您使用always而不是done,您可以使用isResolved()isRejected()检查请求是否成功,例如:

$.when(GetDataFromMethodA(),GetDataFromMethodB(),GetDataFromMethodC())
 .always(function (responseFromMethodA,responseFromMethodB, responseFromMethodC) { 
   if(responseFromMethodA.isRejected()) { 
     console.log('A did not work!'); 
   }
   if(responseFromMethodB.isRejected()) {
     console.log('B did not work!'); 
   }
   // ...etc.
});