创build一个callback函数返回一个数组

我正在学习Node.js

我在创build自己的函数时遇到了麻烦。 这似乎是这样一个简单的事情,但我不太明白如何做到这一点。

该函数传递一个地址(例如:“1234 will ln,co”),该地址使用google的geolocate json api返回数组中的完整地址,纬度和经度。

这是我的代码:

//require secure http module var https = require("https"); //My google API key var googleApiKey = "my_private_api_key"; //error function function printError(error) { console.error(error.message); } function locate(address) { //accept an address as an argument to geolocate //replace spaces in the address string with + charectors to make string browser compatiable address = address.split(' ').join('+'); //var geolocate is the url to get our json object from google's geolocate api var geolocate = "https://maps.googleapis.com/maps/api/geocode/json?key="; geolocate += googleApiKey + "&address=" + address; var reqeust = https.get(geolocate, function (response){ //create empty variable to store response stream var responsestream = ""; response.on('data', function (chunk){ responsestream += chunk; }); //end response on data response.on('end', function (){ if (response.statusCode === 200){ try { var location = JSON.parse(responsestream); var fullLocation = { "address" : location.results[0].formatted_address, "cord" : location.results[0].geometry.location.lat + "," + location.results[0].geometry.location.lng }; return fullLocation; } catch(error) { printError(error); } } else { printError({ message: "There was an error with Google's Geolocate. Please contact system administrator"}); } }); //end response on end }); //end https get request } //end locate function 

所以当我尝试执行我的function

 var testing = locate("7678 old spec rd"); console.dir(testing); 

控制台日志未定义,因为它不等待从定位返回(或至less我猜这是问题)。

我如何创build一个callback,所以当定位函数返回我的数组时,它会在它返回的数组上运行console.dir。

谢谢! 我希望我的问题是有道理的,即时自学,所以我的技术术语是可怕的。

您需要将callback函数传递给您的方法 – 所以callback可能看起来像这样

 function logResult(fullLocation){ console.log(fullLocation) } 

您可以将其与input一起传递给您的locate方法:

 // note: no parentheses, you're passing a reference to the method itself, // not executing the method locate("1234 will ln, co",logResult) 

你也可以这样做内联 – 就像你已经处理的response对象:

 locate("1234 will ln, co",function(fullLocation){ // do something useful here }) 

现在对于你的方法中的那一点,而不是试图return结果,你只需要调用结果的callback:

 function locate(address, callback) { ...... response.on('end', function (){ if (response.statusCode === 200){ try { var location = JSON.parse(responsestream); var fullLocation = { "address" : location.results[0].formatted_address, "cord" : location.results[0].geometry.location.lat + "," + location.results[0].geometry.location.lng }; callback(fullLocation); // <-- here!!! } catch(error) { printError(error); } } else { printError({ message: "There was an error with Google's Geolocate. Please contact system administrator"}); } }); //end response on end ..... } 
Interesting Posts