【问题标题】:How to get data from a different node.js code如何从不同的 node.js 代码中获取数据
【发布时间】:2017-12-20 19:09:57
【问题描述】:

我在 db.js 中有一个代码 sn-p 如下,

    exports.asyncGetAllData = function () {
        connection.connect(function(err) {
            connection.query(sqlGetAllData, function (err, result) {
                if (err) reject(err);
                else
                {
                    //console.log(result);
                }
                });
            });
};

我想在 app.js 中调用函数时获取结果数据,如下所示。

    app.get('/test/getPriceTrend', function(req, res) {
    console.log('SERVER::getPriceTrend');
    console.log(req.url);
    var data = db_connection.asyncGetAllData(); //data is undefined
    console.log(data);
    res.setHeader('Accept', 'application/json');
    res.writeHead(res.statusCode);
    //The following piece of code will send information from the database
    res.write(JSON.stringify({"hello":"world"}));
    res.end();
});

如您所见,当我尝试从 db.js 获取数据时,它在控制台窗口中显示“数据未定义”。我该如何解决这个问题?有什么建议吗?

提前致谢,

【问题讨论】:

标签: javascript node.js rest


【解决方案1】:

最简单的方法是创建一个你传递给asyncGetAllData()的回调函数

你的函数看起来更像这样:

 exports.asyncGetAllData = function (callback) {
    connection.connect(function(err) {
        connection.query(sqlGetAllData, callback)
    })
}

然后在 app.js 中传递回调:

db_connection.asyncGetAllData(function(err, result{
     if (err) reject(err);
     else
     {
             //console.log(result);
     }
})

您还可以调整asyncGetAllData 以返回一个承诺,这可能会使事情变得更漂亮。

【讨论】:

    【解决方案2】:

    看起来您正在使用异步方法调用数据而不是等待响应。

    var data = db_connection.asyncGetAllData(); //data is undefined
    console.log(data);
    

    要么使用可以获取 SyncData 的函数,要么使用如下回调:

       exports.asyncGetAllData = function (cb) {
        connection.connect(function(err) {
            connection.query(sqlGetAllData, function (err, result) {
                if (err) reject(err);
                else
                {
                    //console.log(result);
                    cb(data);
                }
                });
            });
    };
    
    var data = db_connection.asyncGetAllData(function(data) {
        console.log(data);
        res.write(JSON.stringify(data));
        res.end();
    
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-17
      • 1970-01-01
      • 2017-08-19
      • 2020-11-02
      • 2011-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多