2017-04-09 56 views
-1

我想從URL中收集一些JSON數據,並希望在整個Node.js應用程序中使用數據。在下面的代碼中,JSON被正確收集,但變量partOfJson回到未定義狀態。我想這是因爲函數getTheData在完成之前返回theData。在Node.js中返回變量

function getTheData() { 

    const request = require('request'),url = 'myURL'; 

    request(url, (error, response, body)=> { 
      var theData = JSON.parse(body); 
    }); 

    //Do stuff with theData 

    return theData; 
}; 




//Somewere else 
var partOfJson = getTheData(); //I want partOfJson to be parts of the collected JSON 

有沒有人知道如何解決這個問題?我剛開始學習Node.js,所以請放輕鬆點。

+0

只需在您分配的地方添加返回「var theData =」 – Borjante

+0

此問題已被問及約一百次。你還不能返回尚未發佈的數據,它也沒有任何關於node.js的事情。 – 2017-04-09 13:02:22

回答

-1

是的,這是因爲異步性質,您可以使用回調並在回調中返回theData,或者您可以使用promise來獲取值。

回調:

function getTheData(cb){ 
       //get data from your url and store it in theData variable 
       cb(theData) 
       } 

,您可以通過調用函數如下訪問:

getTheData(function(data){ 
      partOfJson=data 
      } 

這樣partOfJson不會是未定義

或者你可以去承諾的方式,這裏是鏈接,讓你開始 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise