如何在另一个生成器函数中访问koa上下文?

node.js KoaJS

神无

2020-04-07

在Koa中,我可以通过this以下第一个生成器函数访问Koa上下文

app.use(function *(){
    this; // is the Context
}

但是,如果我屈服于另一个生成器函数,我将无法this通过它访问上下文

app.use(function *(){
    yield myGenerator();
}

function* myGenerator() {
    this.request; // is undefined
}

我已经能够简单地将上下文传递给第二个生成器函数,但是想知道是否存在一种更干净的方法来访问上下文。

有任何想法吗?

第4155篇《如何在另一个生成器函数中访问koa上下文?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
神乐 2020.04.07

this如您所说,将其中一个作为参数传递

app.use(function *(){
    yield myGenerator(this);
});

function *myGenerator(context) {
    context.request;
}

或使用apply()

app.use(function *(){
    yield myGenerator.apply(this);
});

function *myGenerator() {
    this.request;
}

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android