Javascript 如何在NodeJS中返回异步函数的值并在作用域之外使用

Javascript 如何在NodeJS中返回异步函数的值并在作用域之外使用,javascript,node.js,asynchronous,Javascript,Node.js,Asynchronous,我基本上只想使用异步函数的返回值。我假设变量标记(在下面的代码中)包含异步函数的返回值,但它包含响应。我怎么可能将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

我基本上只想使用异步函数的返回值。我假设变量标记(在下面的代码中)包含异步函数的返回值,但它包含响应。我怎么可能将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?

创建自己的回调函数:

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);

使用回调。或者最好使用Promise(建议试用
bluebird
),您的代码看起来更容易阅读

您可以在允诺后使用
请求
库执行以下操作

request.getAsync(url)
.spread(yourFunction)

yourFunction
将从
requestAsync

获取参数,了解回调和/或承诺-基本上,您需要学习如何为异步函数的异步性质编码这个问题有数百个DUP。nushell中的答案是不能返回异步值。