【问题标题】:UnhandledPromiseRejectionWarning when nesting rest calls嵌套休息调用时出现 UnhandledPromiseRejectionWarning
【发布时间】:2020-06-06 19:35:15
【问题描述】:

我有以下 Rest 调用,其中第二个 rest 调用需要来自第一个调用的数据作为其请求的一部分。 因此,我将它们嵌套如下。 JS/React 的新手,据我尝试阅读,这种嵌套样式 似乎没有被人嫌弃。否则建议。

以下工作基于值“发送电子邮件有效!”这一事实。打印(来自下面的控制台日志)。 此外,由于这次休息电话,按预期收到了一封电子邮件。

我的问题是以下错误消息。为什么我会收到此错误?如果我只打一个休息电话,我不会得到这个 因此相信问题出在我的嵌套上。我当然有如下的 catch 块。 我可以了解为什么会发生这种情况以及如何防止它吗?谢谢。

exports.getData = (req, res) => {
  // 1st rest call  
  axios.post(urls.env.endpoint1, getPostBody1(req.body.code))
    .then((output) => {
      // needed this name value from the first call to be able to pass in the next rest call below. 
      const name = output.data.name_response_data_list[0].short_name;
      console.log(name);
      res.status(200).then(
        // 2nd rest call
        axios.post(urls.env.endpoint2, getPostBody2(name, req.body.email_address))
          .then(() => {
            console.log('Sending Email Worked!');
            res.status(200).send('Success');
          }, () => {
            console.log('bombed....');
          })
      );
    }, (error) => {
      console.log(error);
    });
};

错误信息:

[server:watch] (node:77802) UnhandledPromiseRejectionWarning: TypeError: res.status(...).then 不是函数 [server:watch]
在 axios.post.then (/Users/name/projects/front/src/server/controllers/Controller1.js:77:23) [server:watch] 在 process._tickCallback (internal/process/next_tick.js:68:7) [server:watch] (node:77802) UnhandledPromiseRejectionWarning:未处理的承诺拒绝。这 错误源于在异步函数内部抛出 没有 catch 块,或拒绝未处理的承诺 使用 .catch()。 (拒绝 ID:1)[server:watch](节点:77802)[DEP0018] DeprecationWarning:不推荐使用未处理的承诺拒绝。在 未来,未处理的承诺拒绝将终止 具有非零退出代码的 Node.js 进程。 [server:watch] 发送 电子邮件工作!

【问题讨论】:

标签: javascript node.js reactjs axios


【解决方案1】:

这个错误的原因可能是函数res.status()没有返回Promise,因此它的返回值没有.then()函数。

此外,如果我正确解释了代码,对于每个请求,您将向端点发送两个请求,如果它使用状态代码 200,则回复“成功”。但是,您的代码设置此状态代码两次(一次之后每个端点请求)。我认为这没有任何优势,但是,我不知道您的其余代码。

如果您只想在两个请求都完成后发送状态 200(这是有道理的),您可以简单地删除 res.status(200).then( 并将其更改为

      ...
      const name = output.data.name_response_data_list[0].short_name;
      console.log(name);
      // 2nd rest call
      axios.post(urls.env.endpoint2, getPostBody2(name, req.body.email_address))
      .then(() => {
        console.log('Sending Email Worked!');
        res.status(200).send('Success');
      }, () => {
        console.log('bombed....');
      });
      ...

【讨论】:

  • 这实际上消除了错误。 @charlietfl 传递错误状态将是一个挑战,我想考虑到它可能是 4xx 或 5xx,这与我能够硬编码 200 时的成功不同。
  • @karvai 您可以使用 axios 发布错误对象中的状态,也可以发送您自己的状态
  • @charlietfl 你的意思是这样的:}, error => { console.log('bombed....'); res.status(error.status).send('错误'); });会试一试。谢谢。
  • @karvai 是的。我已经很长时间没有使用 axios 但假设 status 属性与您显示的一样
猜你喜欢
  • 2020-12-05
  • 1970-01-01
  • 2021-08-05
  • 2019-08-17
  • 2019-04-26
  • 2014-10-05
  • 1970-01-01
  • 2014-10-25
  • 1970-01-01
相关资源
最近更新 更多