代码之家  ›  专栏  ›  技术社区  ›  Carol.Kar

在类中使用bind()

  •  0
  • Carol.Kar  · 技术社区  · 5 年前

    我正在上一节课 node-schedule bind() -创建作业队列的函数:

    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
    

    有什么建议可以让我如何将类中的函数绑定到队列?

    谢谢你的回复!

    0 回复  |  直到 5 年前
        1
  •  0
  •   Bergi    5 年前

    没有理由使用 bind 在这里,尤其是没有绑定一个从未使用过的参数数组。也, schedulerLog 是一个方法,一个属性 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);
        }
    }