2015-02-05 19 views
0

如何從異步函數中獲取變量?如何從aysnc函數中獲取變量

我有以下,我想從這個異步函數獲取httpsResp變量。

 var httpsResp; 
     var dfd = this.async(10000); 

     var httpsReq = https.request(httpOptions, dfd.callback(function (resp) { 
      httpsResp = resp.statusCode; 
      assert.strictEqual(httpsResp, correctResp, error.incorrectResp); 
     }), dfd.reject.bind(dfd)); 
     httpsReq.end(); 
     httpsReq.on('error', function(e) { 
      console.error(e); 
     }); 
     console.info('Status Code: ' + httpsResp); 

當前,httpsResp顯示未定義。

+0

[爲什麼我的變量在函數內部修改後沒有改變? - 異步代碼引用](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Barmar

回答

0

正如@Barmar指出的,基本問題已在Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference中得到解答。由於https.request是異步的,因此https.request的調用只是初始化網絡請求並立即返回(即在請求完成之前),然後評估函數中的其餘語句,包括對console.info的調用。 JavaScript中的異步操作不能中斷正在執行的函數,所以直到外部函數返回後纔會調用請求回調。

處理這種情況的常見方法是將任何關心httpsResp值的代碼放入異步回調中。對於一個測試來說,這通常意味着你的代碼已經在做的斷言。