【问题标题】:Retrieve data from request.end() in node.js从 node.js 中的 request.end() 检索数据
【发布时间】:2018-09-18 17:52:10
【问题描述】:

我想在 Node.js 中对另一个文件使用 unirest 请求的结果,但我无法从 request.end() 函数获取数据到外部变量。

代码如下:

request.end(function (response) {
        if(response.error) {
            console.log("AUTHENTICATION ERROR: ", response.error);
        } else {
            callback(null, response.body);
        }

        console.log("AUTHENTICATION BODY: ", response.body);
    });

var result = authentication(function(error, response) {
    var authenticationToken = response.access_token;

    if(authenticationToken != null) {
        console.log("Token: ", authenticationToken);

        return authenticationToken;
    }
});

我想获取 authenticationToken 值以使用 module.exports 导出其他模块。

我正在使用 unirest http 库

【问题讨论】:

    标签: javascript node.js http httprequest unirest


    【解决方案1】:

    它是一个回调函数,被视为参数,而不是返回值的函数。

    你可以这样做:

    var result;
    authentication(function(error, response) {
        var authenticationToken = response.access_token;
    
        if(authenticationToken != null) {
            console.log("Token: ", authenticationToken);
    
            module.exports.result = authenticationToken; // setting value of result, instead of passing it back
        }
    });
    

    您现在可以使用result 变量。 但请注意,它是一个异步函数,因此您可能无法立即使用它,直到在回调函数中为其赋值。

    导出结果值:

    module.exports.result = null;
    

    示例

    m1.js

    setTimeout(() => {
       module.exports.result = 0;
    }, 0);
    
    module.exports.result = null;
    

    app.js

    const m1 = require('./m1.js');
    
    console.log(JSON.stringify(m1));
    
    setTimeout(() => {
      console.log(JSON.stringify(m1));
    
    }, 10);
    

    输出

    {"result":null}
    {"result":0}
    

    因此您可以继续使用变量result,一旦分配了变量,它将包含该值。

    【讨论】:

    • 我得到了相同的结果。 result 变量仍然为空。
    • 函数必须像同步运行一样对待。我怎样才能做到这一点?问题是异步函数。
    • 您的结果为空,因为直到 API 运行后函数才运行..
    猜你喜欢
    • 2020-04-12
    • 1970-01-01
    • 2011-10-26
    • 1970-01-01
    • 2019-02-26
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    • 2016-04-12
    相关资源
    最近更新 更多