gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 22:37:20 26 4
gpt4 key购买 nike

在 Koa 中,我可以通过 this 访问第一个生成器函数中的 Koa Context:

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

但是如果我让步给另一个生成器函数,我就不能再通过 this 访问上下文了。

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

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

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

有什么想法吗?

最佳答案

要么像你说的那样将 this 作为参数传递:

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

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

或使用 apply() :

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

function *myGenerator() {
this.request;
}

关于node.js - 如何在另一个生成器函数中访问 koa 上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26643630/

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