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

标签 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')

最佳答案

您不能像 @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/

相关文章:

javascript - sessionStorage 代理类作用域

javascript - 如何将元素放回到前一个位置?

javascript - 如何识别 Vanilla Picker 的主要全局对象?

javascript - 在单独的函数中使用 Node 中回调的结果

node.js - 模式和模型都正常,但 Mongoose .populate 不起作用

node.js - Jasmine 不加载帮助文件

node.js - 你如何让 mongo 在远程服务器上运行?

javascript - 如何强制用户的鼠标滚动操作到 div,而不是 body?

karma-runner - 每次导入时执行的 ES6 模块代码

javascript - 这个语法: {variable1,variable2,variable3}是什么?