Christopher Holmok
Christopher Holmok

Reputation: 91

Call yield from a promise inside KOA middleware

I am writing a KOA middleware to pull user info from mongo if it's not cached. I am getting the following error:

The "this.getUser" function returns an ES6 promise that fetches the user from mongo if not cached using the request or creates a new anonymous user.

module.exports = function* securityMiddleware(next) {

    this.getUser(this.request)
        .then((user)=>{
            if(user.isAonymous){
                //throw 401 access error
            }else{
                yield next;
            }
        });

};

It's not valid because: jshint says generator has to have a yield and throws a SyntaxError: Unexpected strict mode reserved word.

How do you, in KOA middleware generator do you use promises? I am using KOA v1.2.0.

Upvotes: 1

Views: 703

Answers (2)

zeronone
zeronone

Reputation: 3041

Just to add a little more on @Bergi's answer.

The generator functions used in KoaJS are not pure JS generators. Koa wraps the generators using co underneath, which simulates the async/await semantics using generators (https://github.com/tj/co).

A co-wrapped generator can only yield specific types of Yieldables (including Promise); and processes them asynchronously in the background and return the resulting value (or error) back to the generator function.

Upvotes: 2

Bergi
Bergi

Reputation: 665574

You don't yield inside promise callbacks (which are not generator functions). Instead, you are supposed to just yield the promise itself!

module.exports = function* securityMiddleware(next) {
    var user = yield this.getUser(this.request);
    if (user.isAnonymous) {
        // throw 401 access error
    } else {
        yield next;
    }
};

Upvotes: 1

Related Questions