-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,所以请放轻松点。
只需在您分配的地方添加返回“var theData =” – Borjante
此问题已被问及约一百次。你还不能返回尚未发布的数据,它也没有任何关于node.js的事情。 – 2017-04-09 13:02:22