【问题标题】:Node.js: How to return a rejcted promise without getting UnhandledPromiseRejectionWarningNode.js:如何在没有收到 UnhandledPromiseRejectionWarning 的情况下返回被拒绝的承诺
【发布时间】:2023-03-19 11:50:01
【问题描述】:

我在一个模块中有一个函数,它使用 request-promise-native 模块来查询 couchdb 数据库:

userByEmail: (email) => {
  const options = {
    url: `${config.couchdb.url}/medlog/_design/user/_view/by_email_or_userid?key="${email}"`,
    json: true,
  };

  return rp.get(options)
    .then(users => users.rows.map(row => row.value))
    .catch(reason => Promise.reject(new Error('test')));
}

第二个模块包含一个使用第一个模块的函数:

router.get('/checkEmailExistence', (req, res) => {
  couchdb.userByEmail(req.param('email'))
    .then((userArray) => {
      res.status(200).end(userArray.length > 0); // returns 'true' if at least one user found
    })
    .catch((e) => {
      winston.log('error', e.message);
      res.status(500).end(e.message);
});

在没有数据库连接的情况下,request-promise-native模块的promise被拒绝。我想要的是在第二个函数中捕获该拒绝并将内部服务器错误返回给调用者。为了转发 request-promise-native 模块的拒绝,我在第一个函数中捕获它并返回一个新的拒绝承诺。

不幸的是,我总是收到警告说我有一个未处理的承诺拒绝。我该如何解决这个问题?


编辑

我刚刚发现我使用了错误的代码路径进行测试。所以上面的编码工作而不会产生警告。很抱歉造成混乱。

【问题讨论】:

  • 在第一个模块而不是.catch(reason => Promise.reject(new Error('test')));尝试.catch(reason => new Error('test'));
  • 在这种情况下,我会得到一个通过错误消息解决的承诺。相反,我想得到一个被拒绝的承诺。
  • 您不能在catch 内拒绝,但您可以执行以下操作.catch(reason => throw new Error('test'));
  • 这将停止执行流程 - 这也不应该发生...... ;-)

标签: javascript node.js es6-promise


【解决方案1】:

发生这种情况是因为 Promise 总是必须返回一些东西。

您可以使用 return null

来解决这个“问题”
router.get('/checkEmailExistence', (req, res) => {
  couchdb.userByEmail(req.param('email'))
  .then((userArray) => {
    res.status(200).end(userArray.length > 0); // returns 'true' if at least one user found
    return null
  })
  .catch((e) => {
    winston.log('error', e.message);
    res.status(500).end(e.message);
    return null
  });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    • 2015-10-19
    相关资源
    最近更新 更多