gpt4 book ai didi

javascript - 在协程中包装 ES6 类方法

转载 作者:搜寻专家 更新时间:2023-11-01 00:42:18 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com