0

How do I get a variable out of an async function?

I have the following and I'd like to get the httpsResp variable from this async function.

        var httpsResp;
        var dfd = this.async(10000);

        var httpsReq = https.request(httpOptions, dfd.callback(function (resp) {
           httpsResp = resp.statusCode;
           assert.strictEqual(httpsResp, correctResp, error.incorrectResp);
        }), dfd.reject.bind(dfd));
        httpsReq.end();
        httpsReq.on('error', function(e) {
          console.error(e);
        });
        console.info('Status Code: ' + httpsResp);

Currently, httpsResp shows undefined.

bkuhl
  • 59
  • 1
  • 7
  • possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Barmar Feb 05 '15 at 01:32

1 Answers1

0

As @Barmar points out, the basic question is already answered in Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference. Since https.request is an asynchronous, the call to https.request simply initiates a network request and returns immediately (i.e., before the request is completed), then the remaining statements in your function, including the call to console.info, are evaluated. Asynchronous operations in JavaScript cannot interrupt an executing function, so your request callback won't be called until sometime after the outer function returns.

A common way to handle this situation is to put any code that cares about the value of httpsResp in the asynchronous callback. For a test this generally means assertions, which your code is already doing.

Community
  • 1
  • 1
jason0x43
  • 3,363
  • 1
  • 16
  • 15