javascript - 无法读取 setInterval 中的属性

标签 javascript node.js this setinterval

在 node.js 上我收到错误:

TypeError: Cannot read property 'talk_duration' of undefined

来自:setTimeout(this.hangup, this.data.talk_duration * 1000);setInterval .

但是,在 setInterval 之外我有console.log(this.data.talk_duration);效果很好。

this.outcomeAnswer = function () {

    console.log(this.data.talk_duration); //this work

    num = 0;

    db.run("INSERT INTO in_queue (action_id, state) VALUES ('" + this.data.action_id + "', 'InQueue')", function (error) {
        queueCheckLoop = setInterval(function () {

            num++;

            if (num == 5) {
                clearInterval(queueCheckLoop);
            }

            db.each("SELECT count(*) as total FROM agent_queue WHERE state = 'Ready'", function (err, row) {
                if (row.total > 0) {
                    clearInterval(queueCheckLoop);
                    setTimeout(this.hangup, this.data.talk_duration * 1000);
                }
            });
        }, 1000);
    });
}

最佳答案

您需要记住 this 作为 oucomeAnswer 函数的第一行,例如: var that=this;

然后使用 that.data.talk_duration 在具有不同作用域的函数中。

关于javascript - 无法读取 setInterval 中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32207924/

相关文章:

node.js - 在内连接中使用计数对查询进行序列化

javascript - 使用 this 关键字在对象字面量中未定义属性变量

this - 使用 on() 时如何引用 $(this)

javascript - 为什么我的 Mongoose 查询没有更新 MongoDB 数据库中嵌套数组中的值?

javascript - 根据选中的单选按钮显示幻灯片

php - 在 jQuery 中检索 JSON 响应

javascript - ‘this’ vs. 'bind.(this)' vs. 将事件传递给事件处理程序,React JS vs. vanilla JavaScript

javascript - 如何使数据表工作?

node.js - Auth0 和 Express-openid-connect/回调没有响应

node.js - 动态导入 - import() - 当代码打包成可执行文件时失败