可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I'm trying to create function that can parse JSON from a url. Here's what I have so far:
function get_json(url) { http.get(url, function(res) { var body = ''; res.on('data', function(chunk) { body += chunk; }); res.on('end', function() { var response = JSON.parse(body); return response; }); }); } var mydata = get_json(...)
When I call this function I get errors. How can I return parsed JSON from this function?
回答1:
Your return response;
won't be of any use. You can pass a function as an argument to get_json
, and have it receive the result. Then in place of return response;
, invoke the function. So if the parameter is named callback
, you'd do callback(response);
.
// ----receive function----v function get_json(url, callback) { http.get(url, function(res) { var body = ''; res.on('data', function(chunk) { body += chunk; }); res.on('end', function() { var response = JSON.parse(body); // call function ----v callback(response); }); }); } // -----------the url---v ------------the callback---v var mydata = get_json("http://webapp.armadealo.com/home.json", function (resp) { console.log(resp); });
Passing functions around as callbacks is essential to understand when using NodeJS.
回答2:
In case someone is looking for an solution that does not involve callbaks
function getJSON(url) { var resp ; var xmlHttp ; resp = '' ; xmlHttp = new XMLHttpRequest(); if(xmlHttp != null) { xmlHttp.open( "GET", url, false ); xmlHttp.send( null ); resp = xmlHttp.responseText; } return resp ; }
Then you can use it like this
var gjson ; gjson = getJSON('./first.geojson') ;
回答3:
The HTTP call is asynchronous, so you must use a callback in order to fetch a resultant value. A return
call in an asynchronous function will just stop execution.
function get_json(url, fn) { http.get(url, function(res) { var body = ''; res.on('data', function(chunk) { body += chunk; }); res.on('end', function() { var response = JSON.parse(body); fn(response); }); }); }; get_json(url, function(json) { // the JSON data is here });
In this example, function(json) {}
is passed into the get_json()
function as fn()
, and when the data is ready, fn()
is called, allowing you to fetch the JSON.