簡體   English   中英

無法訪問請求函數JS中的變量

[英]Cannot access variable inside request function JS

我有一個應該返回訪問令牌的函數。 在函數內部有一個請求,它給了我令牌。 但我無法在主函數中訪問它。

這是我在函數內部的代碼:

 var accessToken = 'test1'; request.post(authOptions, function(error, response, body) { accessToken = body.access_token; console.log('test2 ' + accessToken); }); console.log('test3 ' + accessToken);

它給出了以下結果:

測試 3 測試 1

(節點:14744)ExperimentalWarning:stream/web 是一項實驗性功能。 此功能可能隨時更改

(使用node --trace-warnings ...顯示警告的創建位置)

test2 BQDzZHO1Eg99...

accessToken 獲取請求中的值,如 test2 中所示,但是當我在函數之后檢索它時,它還沒有得到它。 之后如何使用? 例如。 在函數中檢索

當您執行request.post您的代碼必須等待您發布到的服務器的響應。 此響應在您的function(error, response, body)函數中處理(作為第二個參數傳入request.post 。但與此同時,您的函數的其余部分將繼續執行。我添加了注釋以嘗試和進一步解釋:

var accessToken = 'test1'; // First line of your code is executed first

// Now we execute request.post
request.post(authOptions, function(error, response, body) {
  // This is only executed whenever the response is received.  It may be many milliseconds later
  accessToken = body.access_token;    
  console.log('test2 ' + accessToken);
});

// This is executed immediately after the `request.post`.  Therefore accessToken will still be 'test1'.
console.log('test3 ' + accessToken);

相反,您可以返回一個Promise或使用回調從該函數中獲取 accessToken。 這是一個基本的回調函數:

function getAccessToken(callback) {
  request.post(authOptions, function(error, response, body) {
    callback(body.access_token);
  });
}

getAccessToken(function(myToken) {
  // Here is your token.
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM