我基本上想要做的就是能够使用异步函数的返回值。我假设变量标签(在下面的代码中)将包含来自异步函数的返回值,但它包含响应。我怎么可能把aRes函数的返回值保存到一个我可以在异步函数范围之外使用的变量中。提前谢谢。
var http = require('http');
var url = "someurl.com"
//async function to be passed to http.get as second parameter
function aRes(response){
var newtag = response.headers.etag;
return newtag;
}
var tag = http.get(url,aRes);
console.log(tag); //logs the response from get request
//tag is not the return value from the ares function but rather the response object. How do I get the return value of that?
答案 0 :(得分:0)
使用回调。或者更好地使用Promise(建议尝试 addresses = geocoder.getFromLocation(lat, lon, 1);
if (addresses != null && !addresses.isEmpty()) {
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName();
}
),您的代码看起来会更容易阅读。
在宣传之后,您可以使用bluebird
库执行以下操作。
request
request.getAsync(url)
.spread(yourFunction)
将从yourFunction
获取args。
答案 1 :(得分:-1)
创建自己的回调函数:
var http = require('http');
var url = "someurl.com";
var aResCallback = function(tag) {
console.log(tag); //logs the response from get request
};
//async function to be passed to http.get as second parameter
function aRes(response){
var newtag = response.headers.etag;
aResCallback(newtag);
return newtag;
}
var tag = http.get(url, aRes);