简体   繁体   中英

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');
  })
});

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.

You can only use yield inside a generator, but the callback that you must pass to Promise 's then is a normal function, that's why you get a SyntaxError.

You can rewrite it as follow:

var authenticated = yield auth.then(function() {
    return true;
}, function() {
    throw new Error('Authentication failed');
})

if (authenticated) yield next

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM