【问题标题】:Parse mysql results into variable with node js使用节点 js 将 mysql 结果解析为变量
【发布时间】:2017-11-15 16:33:08
【问题描述】:

我正在尽力理解 nodeJS/typescript 及其技术。但仍然无法弄清楚如何将我的数据库查询结果保存到变量中并返回它。也许有人可以解释我的问题/帮助我:

我有这样的方法:

public getAllProducts(): ProductArray {
    // returns IConnection from "mysql" and connect
    this.databaseConnection.getConnection().connect();

    var product: any = [];
    this.databaseConnection.getConnection().query('SELECT * FROM product', function (error: any, results:any, fields:any) {
        if (error) throw error;
        product.push(results);
    });



    console.log(product);
    return product;
}

如果有人可以在这里帮助我,那就太好了。

【问题讨论】:

  • 返回产品应该在回调函数内,即 function (error: any, results:any, fields:any) { if (error) throw error; product.push(results);}

标签: javascript mysql node.js typescript callback


【解决方案1】:

您不应该能够从异步函数返回变量。你应该继续阅读一些关于如何对抗回调地狱的文章。所有需要这些数据的逻辑都应该在查询的回调函数中。使用async.js 模块或promises 可以使您的代码看起来更好一些选项(您还可以检查在nodeSJ 7.6.0 版本上添加的async/await。

【讨论】:

  • Promise 是这里的必经之路,除非你准备好使用最新 Node 中的新 async 功能。
  • 好的,谢谢您的回答!因此,只要我想查询某些内容,我就需要在函数内部执行所有操作?从请求到响应?
  • 这就是回调地狱术语被赋予生命的方式。继续检查承诺如何防止这种情况发生。
猜你喜欢
  • 2016-12-25
  • 2018-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-23
  • 1970-01-01
相关资源
最近更新 更多