我希望将类方法制作成协程:
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')
最佳答案
您不能像 @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();
});
}
}
关于javascript - 在协程中包装 ES6 类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30406933/