如何从异步函数中获取变量

时间:2015-02-05 01:30:16

标签: intern

如何从异步函数中获取变量?

我有以下内容,我想从这个异步函数中获取httpsResp变量。

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

目前,httpsResp显示未定义。

1 个答案:

答案 0 :(得分:0)

正如@Barmar指出的那样,Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference已经回答了基本问题。由于https.request是异步的,因此对https.request的调用只是启动网络请求并立即返回(即,在请求完成之前),然后是函数中的其余语句,包括对{{{{1}的调用1}},被评估。 JavaScript中的异步操作不能中断正在执行的函数,因此在外部函数返回之后的某个时间才会调用请求回调。

处理这种情况的一种常见方法是在异步回调中放置任何关心console.info值的代码。对于测试,这通常意味着断言,您的代码已经在进行。