2017-08-04 78 views
0

我已經檢查了關於這個問題的所有類似問題,但仍然無法弄清楚它應該如何工作。任何人都可以帶領我走向正確的方向。 data和data2沒有按時加載,但在跳過$ .when之後,它們出現在chrome調試器中。提前致謝。JQuery兩個不同的異步ajax調用返回undefined

function First (number) {  
    return $.ajax({ 
     url: "/…", 
     data: { 'number': number }, 
     type: "POST", 
     cache: "False", 
     success: function (data) { 
      return data; 
     }, 
     error: function (xhr, type) { 
      alert('Something went wrong.') 
     } 
    }); 
} 

function Second (number) {  
    return $.ajax({ 
     url: "/…", 
     data: { 'number': number }, 
     type: "POST", 
     cache: "False", 
     success: function (data2) { 
      return data2; 
     }, 
     error: function (xhr, type) { 
      alert('Something went wrong.') 
     } 
    }); 
} 

function DoSomeBusiness(number) { 
    $.when(First(number), Second(number)).then(function (data, data2) { 
     var someData = data; // data and data2 is undefined for sometime but right after I pass this line of code they appear correctly but i cannot use them cause they’re not loading on time. 
     var someData2 = data2;   
    });  

    .. do some business   
}; 
+0

可能重複的[如何從異步調用返回響應?](https://stackoverflow.com/questions/14220321/how-do-我回復了異步調用的響應) – Liam

+0

@Liam OP正在使用Promise和'$ .when()',所以恕我直言不正確的dup目標 – Satpal

+0

[答案]中有一整段(https:/ /stackoverflow.com/a/14220323/542251)* ES2015 +:承諾然後()* @Satpal – Liam

回答

-1

不要在Ajax調用使用成功/錯誤域,您應在回調。然後管理這些

編輯: 和緩存字段應該是一個布爾

EDIT2: 問題不是很清楚,我認爲問題是這些回調中的一個干擾延期行爲,因爲代碼看起來很好。 也許OP要訪問數據和數據2,他寫

.. do some business  

,這是一個錯誤,因爲無論有沒有得到無論是在回調。那麼之前執行。 因此,OP只是將您的代碼在回調中,它應該工作

+0

擴展到第一行......成功中的「return」不做任何事情,也不是承諾鏈的一部分 – charlietfl