【发布时间】:2017-09-04 12:23:28
【问题描述】:
我正在尝试从 URL 收集一些 JSON 数据,并希望在整个 Node.js 应用程序中使用这些数据。在下面的代码中,JSON 被正确收集,但变量 partOfJson 返回为未定义。我猜这是因为函数 getTheData 在完成之前返回了 theData。
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,所以请放轻松。
【问题讨论】:
-
只需在您分配“var theData=" 的位置添加返回
-
这个问题已经被问了大约一百次了。还没来的数据是不能返回的,跟node.js也没关系。
标签: javascript node.js callback return