【问题标题】:Expected to return a value at the end of arrow function consistent-return期望在箭头函数一致返回的末尾返回一个值
【发布时间】:2020-05-06 08:48:09
【问题描述】:
exports.create = (req, res) => {
  if (!req.body.task) {
    return res.status(400).send({
      message: "Task Can't be empty",
    });
  }
  const task = new Task({
    task: req.body.task,
  });
  task.save()
    .then((data) => {
      res.send(data);
    })
    .catch((err) => {
      res.status(500).send({
        message: err.message || 'Some error occurred while creating the Task.',
      });
    });
};

这是我的函数,我尝试了不同的返回方式,但 O 仍然得到错误:

期望在箭头函数consistent-return结束时返回一个值 1:29。

谁能帮我解决这个问题?

【问题讨论】:

  • 我不知道你的问题,但也许你可以尝试在 res.send 和 res.status 之前添加 return。查看第三行,在其中添加 return res.status(400)。也许你应该做另一个 res。

标签: javascript express eslint eslint-config-airbnb


【解决方案1】:

return 添加到您的task.save() 的thencatch 箭头函数中也可以这样:

task.save().then((data) => {
  return res.send(data);
})
.catch((err) => {
  return res.status(500).send({
    message: err.message || 'Some error occurred while creating the Task.',
  });
});

【讨论】:

  • 我能做到,是的,虽然我以前做过,但这是正确的答案。
【解决方案2】:

我认为您的 create 函数不需要返回特定值,因此请确保您在其中拥有的唯一 return 没有价值。

变化:

return res.status(400).send({
  message: "Task Can't be empty",
});

到:

res.status(400).send({
  message: "Task Can't be empty",
});
return;

【讨论】:

    猜你喜欢
    • 2021-11-09
    • 2022-01-20
    • 2021-01-15
    • 2022-11-17
    • 1970-01-01
    • 2021-11-22
    • 1970-01-01
    • 2020-10-14
    • 1970-01-01
    相关资源
    最近更新 更多