0

All I basically want to do is to be able to use the return value from an asynchronous function. I assumed the variable tag (in the code below) would contain the return value from the async function but it rather contains the response. How could I possibly get hold of the return value from the aRes function into a variable that I can use outside the scope of the async function. Thank you in advance.

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?
  • learn about callbacks and/or promises - basically, you need to learn how to code for the asynchronous nature of asynchronous functions – Jaromanda X Nov 06 '15 at 04:52
  • There are hundreds of dups of this question. The answer in a nushell is that you can't return an async value. – jfriend00 Nov 06 '15 at 04:56

2 Answers2

0

Use callback. Or better yet use Promise (recommend trying out bluebird), your code will look easier to read.

You can do something like below with request library after promisify it.

request.getAsync(url)
.spread(yourFunction)

yourFunction will take args from requestAsync.

Tuan Anh Tran
  • 6,807
  • 6
  • 37
  • 54
-1

Create your own callback function:

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);
Jason Byrne
  • 1,579
  • 9
  • 19