javascript - 使用 Node.js 和 MySQL 查询函数回调的范围

标签 javascript mysql node.js

我正在尝试使用 Node 和 MySQL 编写一个 JavaScript 对象作为购物任务的一部分。我想通过让它比函数式编程更面向对象来测试自己。我正在为一个交易对象创建一个构造函数,该对象具有所选项目、所需数量和总成本的属性。此外,还有显示项目、选择项目和购买项目的方法。

一开始,我还想拥有一组唯一的 itemID,以验证用户选择了有效的产品。我有一个范围界定问题,如果在对象的范围内定义,则 this.ids[] 是未定义的。我下面的解决方案是在本地定义它并将该数组作为参数传递以避免范围界定。该解决方案也不允许我访问 Transaction 对象的作用域变量。

this.listProducts = function(connection) {
    connection.query("SELECT * FROM products WHERE stock_quantity>0", function(err,res) {
        if (err) throw err;
        this.ids = [];
        for (var i = 0; i < res.length; i++) {
            this.ids.push(res[i].item_id);
            console.log(res[i].item_id + " " + res[i].product_name + " " + res[i].price);
        }
        // res.forEach(function (element) {
        //  console.log("this.ids=",this.ids);
        //  this.ids.push(element.item_id);
        //  console.log(element.item_id + " " + element.product_name + " " + element.price);
        // });
        connection.end();
        console.log(this.totalCost, this.ids);
    });
};

我试过了

         ....
         console.log(this.totalCost, this.ids);
    });
}.call(this);

我得到 TypeError: connection.query(...).call is not a function

我的范围界定是否一团糟?如何解决范围问题,以便我可以访问“事务”对象的范围?

如果我的问题措辞不连贯,请告诉我...

最佳答案

我相信这里有两个选项可供您使用

arrow将 this 绑定(bind)到定义它的任何地方的函数。

this.listProducts = function(connection) {
    var that = this;
    connection.query("SELECT * FROM products WHERE stock_quantity>0", 
     //use arrow instead of anonymous function
     (err,res) => {
        if (err) throw err;
        this.ids = [];
        for (var i = 0; i < res.length; i++) {
            this.ids.push(res[i].item_id);
            console.log(res[i].item_id + " " + res[i].product_name + " " + res[i].price);
        }
        connection.end();
        console.log(this.totalCost, this.ids);
    });
}

或像这样存储this引用

this.listProducts = function(connection) {
    var that = this;
    connection.query("SELECT * FROM products WHERE stock_quantity>0", function(err,res) {
        if (err) throw err;
        that.ids = [];
        for (var i = 0; i < res.length; i++) {
            that.ids.push(res[i].item_id);
            console.log(res[i].item_id + " " + res[i].product_name + " " + res[i].price);
        }
        connection.end();
        console.log(that.totalCost, that.ids);
    });
}

关于javascript - 使用 Node.js 和 MySQL 查询函数回调的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46225219/

相关文章:

mysql - 在 Mac OSX 10.7.5 上安装 MySQL 服务器,尝试访问 MySQL 时收到 1045 (28000) 错误

javascript - 如何在开发模式下运行 hyperledger-fabric Node js 链代码?

javascript - 解释 $apply 和 $eval |我可以用其他功能代替它们吗? AngularJS

javascript - 删除 HTML5 视频上的黑色加载闪光

javascript - Xul:用垂直盒子动态填充水平盒子会导致元素垂直放置

mysql - 优化SQL : Customers that haven't ordered for x days

javascript - 如何用文本替换播放/暂停图标切换

mysql - 谁能解释这个 MySQL 错误?

javascript - 按顺序执行多个 Promise(概念)

arrays - 检查两个数组中的 JSON 属性