Search code examples
javascriptgeneratorkoakoa-router

How do you run `yield next` inside a promise or callback?


I'm stuck writing an authentication router for a koa app.

I have a module that gets data from the DB then compares it to the request. I want to only run yield next if the authentication passes.

The problem is that the module that communicates with the DB returns a promise and if I try to run yield next inside that promise I get an error. Either SyntaxError: Unexpected strict mode reserved word or SyntaxError: Unexpected identifier depending on whether or not strict mode is used.

Here's a simplified example:

var authenticate = require('authenticate-signature');

// authRouter is an instance of koa-router
authRouter.get('*', function *(next) {
  var auth = authenticate(this.req);

  auth.then(function() {
    yield next;
  }, function() {
    throw new Error('Authentication failed');
  })
});

Solution

  • I think I figured it out.

    The promise needs to be yielded which will pause the function until the promise has been resolved then continue.

    var authenticate = require('authenticate-signature');
    
    // authRouter is an instance of koa-router
    authRouter.get('*', function *(next) {
      var authPassed = false;
    
      yield authenticate(this.req).then(function() {
        authPassed = true;
      }, function() {
        throw new Error('Authentication failed');
      })
    
      if (authPassed)  {
       yield next;
      }
    });
    

    This seems to work, but I'll update this if I run into any more problems.