How to access koa context in another generator function?
Asked Answered
F

1

5

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?

Fetus answered 30/10, 2014 at 1:37 Comment(0)
B
12

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;
}
Bodleian answered 30/10, 2014 at 3:16 Comment(2)
Works like a charm. Cheers Vinicius!Fetus
What if my generator function has other arguments I want to pass in?Sainted

© 2022 - 2024 — McMap. All rights reserved.