【问题标题】:How do you run `yield next` inside a promise or callback?如何在 Promise 或回调中运行 `yield next`?
【发布时间】:2023-04-08 00:36:01
【问题描述】:

我一直在为 koa 应用程序编写身份验证路由器。

我有一个模块从数据库中获取数据,然后将其与请求进行比较。如果身份验证通过,我只想运行yield next。

问题是与数据库通信的模块返回一个承诺,如果我尝试在该承诺内运行yield next,我会收到一个错误。 SyntaxError: Unexpected strict mode reserved word 或 SyntaxError: Unexpected identifier 取决于是否使用严格模式。

这是一个简化的例子:

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

【问题讨论】:

    标签: javascript generator koa koa-router


    【解决方案1】:

    我想我明白了。

    需要产生承诺,这将暂停函数,直到承诺得到解决,然后继续。

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

    这似乎可行,但如果我遇到任何问题,我会更新它。

    【讨论】:

      猜你喜欢
      • 2017-08-19
      • 2018-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-19
      • 2021-02-01
      • 1970-01-01
      相关资源
      最近更新 更多