在协同程序中包装ES6类方法

时间:2015-05-22 22:47:32

标签: javascript node.js ecmascript-6

我希望将一个类方法变成一个协程:

import co from 'co';

class AClass {
    co(*consutrctor() {
       console.log('is something like this possible?');
    })

    co(*get() {
        console.log('what about this?');
    })

    onlyWay() {
        return co(function* () {
            console.log('this is how I do it now');
        }.bind(this))();
    }
}

在python中,装饰器很容易:

from asyncio import coroutine

class AClass(object):
    @coroutine
    def get(self):
        print('some async task')

1 个答案:

答案 0 :(得分:3)

您不能使用生成器函数,因为@FelixKling说但是正确的方法来执行您尝试的操作(在我看来),是这样的:

import co from 'co';

class AClass {
    constructor() {
        const a = this;
        co(function* () {
           // "a" contains a reference to the class.
           console.log(a...);
        });
    }

    *get() {
        // this is a yieldable generator function and you can use "co" here too.
    }

    onlyWay() {
        // still better to use this in my opinion:
        const a = this;
        co(function* () {
            yield a.get();
        });
    }
}