2015-09-07 64 views
0

我有問題。過去3個小時,我一直在試圖弄清楚這一點,而我不知道爲什麼這不起作用,我期待它。請知道,我還是很新的Javascript,所以我很抱歉,如果有什麼是明顯的。Nodejs Request Return Misbehaving

有了這段代碼,我試圖從Twitter獲取一個不記名令牌,但是,return bodyconsole.log(body)返回2完全不同的東西。

當我console.log(body),我得到的輸出我想到:

{"token_type":"bearer","access_token":"#####"} 

不過,如果我return body,我得到的http請求的JSON。我在下面粘貼了我的代碼,我希望有人能夠提供幫助。

var request = require('request'); 

var enc_secret = new Buffer(twit_conkey + ':' + twit_consec).toString('base64'); 
var oauthOptions = { 
    url: 'https://api.twitter.com/oauth2/token', 
    headers: {'Authorization': 'Basic ' + enc_secret, 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'}, 
    body: 'grant_type=client_credentials' 
}; 

var oauth = request.post(oauthOptions, function(e, r, body) { 
    return body; 
}); 

console.log(oauth) 

回答

1

異步,異步,異步。

您不能從函數返回異步操作的結果。該函數早已在調用異步回調之前返回。因此,消費request.post()結果的唯一地方就是INSIDE回調本身,並通過調用該回調中的其他函數並將數據傳遞給其他函數。

var oauth = request.post(oauthOptions, function(e, r, body) { 
    // use the result here 
    // you cannot return it 
    // the function has already returned and this callback is being called 
    // by the networking infrastructure, not by your code 

    // you can call your own function here and pass it the async result 
    // or just insert the code here that processes the result 
    processAuth(body); 
}); 

// this line of code here is executed BEFORE the callback above is called 
// so, you cannot use the async result here 

僅供參考,這是新的Node.js/JavaScript開發人員一種很常見的學習問題。要在節點中編碼,您必須學習如何使用這種異步回調。

+0

感謝您的評論,但我不確定如何做到這一點。 我需要能夠'JSON.parse(body).access_token',然後將輸出存儲在一個變量中,這樣我可以在初始化twitter時調用它。 如果我要從變量中分離出這個函數,並且在裏面移動這個變量,我將無法在函數外部調用該變量。我將如何能夠實現這一目標? –

+0

@KurisuBrooks - 異步時間是完全不確定的。結果可能在1秒內可用,或者可能在4分鐘內可用。因此,使用結果的唯一方法是在您知道現在可用的回調中。如果你想用它初始化twitter,那麼你可以在這個回調中調用twitter初始化。這可能看起來並不像你想要構建的東西,但它是你必須用異步結果做事情的方式。 – jfriend00

+0

我明白了,非常感謝。我試圖將我的Twitter身份驗證密鑰保存在一個單獨的文件中,當我同步時,它並未提交給git,但它看起來像是不可避免的。我可能需要研究async的工作方式,但您一直非常樂於幫助。感謝一堆:) –

相關問題