javascriptnode.jsecmascript-6co

How do I get away from using the `self = this` hack when using ES6 classes and generator functions?


I have tried to use the explicit .bind(this) and that did not work. I also know arrow functions dont work here.

'use strict';

const co     = require('co');

class ServiceDemo {

    constructor(repository, config, loggingService) {
        this.config = config;
        this.repository = repository;
        this.loggingService = loggingService;
    }

    checkForNotifications(pricePoint) {

        const self = this;

        return co(function*() {
            self.loggingService.debug('test');
            //const surprisesToNotify = yield this.getSomething(pricePoint);
        });
    }

    getSomething(){
        return co(function*() {
            return {};
        });
    }

}

module.exports = SurpriseSchedulerService;


Solution

  • co will use the context it's called with when it calls the generator:

    co.call( this, function*() {
        this.loggingService.debug('test');
    });