【问题标题】:Avoid promise was created not returned from it when calling next() inside promise chain [duplicate]在promise链中调用next()时避免创建promise而不是从它返回[重复]
【发布时间】:2020-02-14 00:44:53
【问题描述】:
function isAuthenticated() {
    return compose()
        .use(function(req, res, next) {
            if (!req.headers.authorization) {
                return res.status(200).send({ status: 'failure', data: [], message: 'Please login to perform this action' });
            }
            try {
                const token = req.headers.authorization;
                const decoded = jwt.verify(token, process.env.SECRET_KEY);

                User.findOne({ where: { id: decoded.id } }).then(userFound => {
                    if (userFound) {
                        req.user = userFound;
                        next();
                    } else {
                        return res.json({ status: 'failure', data: [], message: 'Unauthorised.' });
                    }
                }).catch(e => {
                    return res.json({ status: 'failure', data: [], message: 'Unauthorised' });
                });
            } catch (error) {
                return res.json({ status: 'failure', data: [], message: 'Authentication failed' + error.message });
            }
        });
};

它显示如下警告:

(node:9900) 警告:在 /home/nodejs/server/auth/auth.service.js:23:25 的处理程序中创建了一个承诺,但没有从它返回,请参阅

我该如何处理这些警告,我尝试在不同的地方使用 return 语句,但没有解决。

【问题讨论】:

  • 你不需要return User.findOne吗?
  • 我试过但仍然显示相同的警告
  • 如果你创建函数async你可以await userFound = User.findOne(...);代替。
  • return null 放在next() 调用之后。

标签: javascript node.js sequelize.js bluebird


【解决方案1】:

您错过了以下部分的退货声明:

User.findOne({ where: { id: decoded.id } }).then(userFound => {
   if (userFound) {
      req.user = userFound;
      next();
      // I guess here the code should return as well
   } else {
      return res.json({ status: 'failure', data: [], message: 'Unauthorised.' });
   }
}

来自文档:

这通常意味着您只是在某处忘记了 return 语句,这将导致未连接到任何 Promise 链的失控 Promise。

请在此处查找来源:Warning: a promise was created in a handler but was not returned from it

【讨论】:

    猜你喜欢
    • 2017-10-31
    • 1970-01-01
    • 2021-03-17
    • 1970-01-01
    • 2021-02-06
    • 2017-03-17
    • 2023-04-02
    • 1970-01-01
    • 2018-12-14
    相关资源
    最近更新 更多