2017-01-18 40 views
0

所以我目前正在使用一個API的程序工作。JavaScript - 不能從onload函數獲取數據(http請求)

我有兩個功能ATM:

getBotID()

function getBotID(domain) { 
    var url = "http://" + domain + ":8087/api/v1/botId"; 
    idRequest.open("GET", url); 
    idRequest.onload = function() { 
     var botID = JSON.parse(idRequest.responseText); 
    }; 
    idRequest.send(); 
} 

和getAuth()

function getAuth(domain, user, pass) { 
    getBotID(domain); 

    var url = "http://" + domain + ":8087/api/v1/bot/login"; 
    body = '{"username": ' + user + ', "password": ' + pass + ', "botId": ' + botID + '}'; 
    authRequest.open("POST", url); 
    authRequest.setRequestHeader("Content-Type", "application/json"); 
    authRequest.onload = function() { 
     var authToken = JSON.parse(authRequest.responseText); 
    }; 
    authRequest.send(JSON.stringify(body)); 
} 

我必須得到BOTID之前,我可以嘗試得到一個新的authToken所以我立即在getAuth()函數中調用getBotID()。

我的問題是:我不能得到BOTID在getBotID(http請求的onload()函數之外),因爲它會像這樣運行:

  1. 開始getAuth()
  2. 啓動getBotID()
  3. 完成getBotID()
  4. 完成getAuth()
  5. ,現在可以getBotID()的onload功能...

我只是不能從onload函數獲取botID數據。我已經試圖給你一個回調函數,但沒有奏效。

+0

你不能那樣做。你應該使用承諾。 – SLaks

+0

不要手動構建JSON。使用'JSON.stringify'。 – SLaks

+0

@SLaks你的意思是身體變量? – redii

回答

1

我認爲這會奏效。傳遞一個匿名函數來getBotId並將它調用回你的第一個請求完成後:

function getBotID(domain, callback) { 
    var url = "http://" + domain + ":8087/api/v1/botId"; 
    idRequest.open("GET", url); 
    idRequest.onload = callback; 
    idRequest.send(); 
} 

function getAuth(domain, user, pass) { 
    getBotID(domain, function() { 
    var botID = JSON.parse(this.responseText); 
    var url = "http://" + domain + ":8087/api/v1/bot/login"; 
    body = '{"username": ' + user + ', "password": ' + pass + ', "botId": ' + botID + '}'; 
    authRequest.open("POST", url); 
    authRequest.setRequestHeader("Content-Type", "application/json"); 
    authRequest.onload = function() { 
     var authToken = JSON.parse(authRequest.responseText); 
    }; 
    authRequest.send(JSON.stringify(body)); 
    }); 
} 
+0

我會試試這個!似乎聰明沒有想到使用像這樣的回調 – redii

0

所以最簡單的方法是將「假」參數添加到getBotIDs idRequest.open()函數。這將導致代碼同步,onload()函數將在其餘代碼運行之前完成。

+0

不要這樣做;這將完全凍結瀏覽器。 – SLaks

+0

嗯,我沒有測試,但迄今爲止,我與Electron合作,也許我可以在「登錄屏幕」後啓動一個新窗口。 – redii

+0

不需要。您需要了解如何編寫異步代碼。閱讀http://blog.slaks.net/2015-01-04/async-method-patterns/ – SLaks