Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access koa context in another generator function?

Tags:

node.js

koa

In Koa I can accesss a Koa Context in the first generator function via this:

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

But if I yield to another generator function I can't access the context via this anymore.

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

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

I've been able to simply pass the context to the second generator function, but was wondering whether there's a cleaner way to access the context.

Any ideas?

like image 718
Felix Avatar asked Oct 30 '14 01:10

Felix


1 Answers

Either pass this as an argument as you said:

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

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

or use apply():

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

function *myGenerator() {
    this.request;
}
like image 164
Vinicius Pinto Avatar answered Oct 13 '22 03:10

Vinicius Pinto