在类中使用bind()

时间:2019-05-10 20:12:51

标签: javascript

我正在使用node-schedulebind()函数创建作业队列的班级:

class Test {

    constructor() {}

    schedulerLog(value) {
        this.ipcRenderer.send('job-log', process.pid + ': ' + value);
    }

    async initScheduler() {

        try {
            let dt = new Date(el.scheduled_time)
            let db = this.knex // one knex instance per scheduled job

            this.schedule.scheduleJob(dt, function () {
                // When job is running update the status of the job in the db
                let sc = new ScheduledContent(db)
                el.status = "sent" // set status to "sent"

                sc.createOrUpdateContent(el.id, el.title, null, el.scheduled_time, el.image, el.status).then((res) => {
                    schedulerLog('Job-ID #' + el.id + ' -- ' + el.title + ' -- executed at: ' + dt + " -- and updated: " + res);
                })
            }.bind(null, [db, schedulerLog]));
            this.schedulerLog("\n Number of Jobs Scheduled: " + Object.keys(this.getQueue()).length + "\n");
        } catch (error) {
            this.schedulerLog(error);
        }
    }
}

module.exports = {
    Test
};

但是,使用.bind(null, [db, schedulerLog])时出现错误:

ReferenceError: schedulerLog is not defined

有人建议我如何仍可以将类中的函数绑定到队列吗?

感谢您的答复!

1 个答案:

答案 0 :(得分:0)

这里没有理由使用bind,尤其是没有理由绑定从未使用过的参数数组。另外,schedulerLog是一种方法,是this的属性,而不是局部变量-这就是为什么您会得到异常的原因。您所需要做的就是使用闭包和箭头函数来保持this上下文:

initScheduler() { // no need for async here

    try {
        let dt = new Date(el.scheduled_time)
        let db = this.knex

        this.schedule.scheduleJob(dt, async () => { // arrow function!
            let sc = new ScheduledContent(db)
            el.status = "sent"

            let res = await sc.createOrUpdateContent(el.id, el.title, null, el.scheduled_time, el.image, el.status)
//                    ^^^^^ use async/await instead of .then() here
            this.schedulerLog('Job-ID #' + el.id + ' -- ' + el.title + ' -- executed at: ' + dt + " -- and updated: " + res);
//          ^^^^^ call method on this
        });
        this.schedulerLog("\n Number of Jobs Scheduled: " + Object.keys(this.getQueue()).length + "\n");
    } catch (error) {
        this.schedulerLog(error);
    }
}