【问题标题】:Unhandled Promise rejection of a property undefined未处理的 Promise 拒绝属性未定义
【发布时间】:2017-11-13 17:29:34
【问题描述】:
setInterval(function(){

    for(i=1;i<=len;i++)
    {

        plug[i].getSysInfo().then(data => {

            var json = JSON.stringify(data,undefined,2);

            var obj = JSON.parse(json);
            var _macadd = obj.mac;

            plug[i].getConsumption().then(data => {

                var json = JSON.stringify(data,undefined,2);
                var obj = JSON.parse(json);
                var _current = obj.current;
                var _voltage = obj.voltage;
                var _power = (obj.power).toPrecision(5);
                var _total = obj.total;
                var _err_code = obj.err_code;
                console.log(_power);
                //console.log(_macadd);
                //console.log(voltage);
                if(_power > 1800)
                {
                    _power = 0.00;
                }
                //  var fs = require('fs');
                //  fs.writeFile("emeter.json", json);

                var sql1 = "INSERT INTO emeter SET ? ";
                var post1  = { macaddress: _macadd,current: _current,voltage: _voltage,power: _power, total: _total,err_code: _err_code};


                var tmp = JSON.stringify(post1,undefined,2);
                console.log(tmp);
                con.query(sql1, post1, function (err, result) {
                    if (err) throw err;
                    console.log("inserted");
                });

            });
        });
    }

},30000);

当我运行这个时,我遇到了错误 未处理的承诺拒绝类型错误: Cannot read property of 'getconsumption' of undefined.

当我用一个值替换索引时,上面的代码运行良好。仅检索一个值它正在工作。当它处于 For 循环中时,将返回错误消息。请帮我解决这个问题。

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    您正在尝试在异步回调中使用 for 循环索引值。问题是.then() 处理程序是在for 循环已经完成之后调用的,因此当您尝试使用它时,for 循环索引处于其终端值(超出数组末尾)。

    有很多方法可以解决这个问题。一种简单的方法是改变这一点:

    for(i=1;i<=len;i++)
    

    到这里:

    for(let i=1;i<=len;i++)
    

    使用 ES6 let 为 for 循环的每次执行创建一个新的唯一变量,以便每个人都维护自己的索引副本,即使在该 for 循环块内的异步调用期间也是如此。


    在 ES5 中(您没有 let),您可以更改循环以使用 .forEach():

    plug.forEach(function(val, index) {
        // use val and index here rather than plug[i]
    });
    

    这还会为循环的每次调用创建一个新的val 和index 变量。

    【讨论】:

      猜你喜欢
      • 2021-07-26
      • 2019-04-07
      • 2018-03-19
      • 1970-01-01
      • 2019-07-19
      • 2019-06-03
      • 2020-04-09
      • 2019-11-13
      • 2021-10-19
      相关资源
      最近更新 更多