2016-07-26 114 views
1

我一直在努力解決這個問題,並且無法弄清楚如何讓一個函數在兩個函數結果中繼續執行,並在兩個函數完成後立即執行。2個函數完成後在JQuery中執行一個函數

我試着這樣做:

$.when(SetCountryAndLanguage(), GetUserRoles()).done(SetInlineManualTracking()); 

不過是去SetInlineManualTracking()馬上無需等待到2層的功能來完成他們的工作。 如何在兩個函數完成後執行第三個函數,同時保持異步優勢?

這是函數數1:

//Gets the country the user is in and later set the player language. 
      function SetCountryAndLanguage() { 
       $.get("http://ipinfo.io", function() {}, "jsonp"). 
        done(function(response) { 
         inlineCountry = response.country; 
        }). 
        done(SetInlineManualLanguage); 
      } 

功能編號2:

//Gets the user roles from the db and update the tracking. 
      function GetUserRoles() { 
       debugger; 
       $.ajax({ 
         type: "POST", 
         url: "../Publisher/Service.asmx/SelectUserRoles", 
         contentType: "application/json; charset=utf-8", 
         dataType: "json" 
        }). 
        done(UpdateRoles); 
      } 

而這依賴於其他2個前面的函數第三個功能:

function SetInlineManualTracking() { 
       debugger; 
       //<!-- User tracking data --> 
       window.inlineManualTracking = { 
        uid: inlineUid, // Only this field is mandatory 
        email: Cookies.get('email'), 
        username: inlineUserName, 
        name: Cookies.get('name'), 
        created: new Date().getTime()/1000, 
        updated: new Date().getTime()/1000, 
        group: inlineCountry, 
        roles: userRoles 
       } 
      } 
+1

執行函數而不是傳遞它們的引用,在每個函數中返回'$ .ajax'的承諾,並將'SetInlineManualTracking'的引用傳遞給'done()' –

+0

@RoryMcCrossan你能告訴我你的代碼是什麼意思嗎? ? –

+0

我爲你添加了一個答案 –

回答

1

您需要使您執行的功能返回$.get和的承諾。然後,您需要將SetInlineManualTracking的參考提供給done(),而不是立即執行。嘗試這個。

$.when(SetCountryAndLanguage(), GetUserRoles()).done(SetInlineManualTracking); 

function SetCountryAndLanguage() { 
    return $.get("http://ipinfo.io", function() {}, "jsonp").done(function(response) { 
     inlineCountry = response.country; 
    }).done(SetInlineManualLanguage); 
} 

function GetUserRoles() { 
    return $.ajax({ 
     type: "POST", 
     url: "../Publisher/Service.asmx/SelectUserRoles", 
     contentType: "application/json; charset=utf-8", 
     dataType: "json" 
    }).done(UpdateRoles); 
} 

注意爲SetInlineManualLanguageUpdateRolesSetInlineManualTracking是在請求done處理程序,他們可以在同一時間執行。這不應該是一個問題,除非其中一個依賴於另一個的結果。

+0

現在,它的工作原理,我明白我需要通過AJAX承諾。 –

相關問題