Http响应未在承诺链中发送

问题描述 投票:0回答:1

在下面的代码中,尽管控制台上显示了消息“ Hello there”,但我没有在前端收到HTTP响应。显然,我缺少了一些东西,但是有人可以指出吗?

而且,更笼统地说,我不确定像这样链接then是好的做法。可以吗?

exports.updateUserProfile = (req, res) => {
  const userId = req.body.id;
  const password = req.body.password;
  const newIds = req.body.newIds;

  userService.isPasswordValid(userId, password)
    .then(
      isValid => {
        if (isValid) {
          return isValid;
        } else {
          return res.status(401).json({
            message: 'Invalid password.'
          });
        }
      })
    .then(
      () => {
        return userService.getFieldsToUpdate(newIds);
      })
    .then(
      update => {
        console.log('update: ', update);
        return User.updateOne(
          { _id: userId },
          update
        );
      })
    .then(
      () => {
        res.status(200).json({
          message: 'User profile successfully updated.'
        });
        console.log('hello there!');
      })
    .catch(
      err => {
        return res.status(400).end({
          message: err
        });
      }
    );
}
javascript httpresponse
1个回答
0
投票

您可以尝试这个

exports.updateUserProfile = async (req, res) => {
  const userId = req.body.id;
  const password = req.body.password;
  const newIds = req.body.newIds;
  try {
    const isValid = await userService.isPasswordValid(userId, password);
    if(!isValid)
      return res.status(401).json({message: 'Invalid password.'});
    const update = await userService.getFieldsToUpdate(newIds);
    console.log('update: ', update);
    await User.updateOne({ _id: userId }, update);
    return res.status(200).json({message: 'User profile successfully updated.'});
    console.log('hello there!');
  } catch(e) {
      return res.status(400).end({ message: e.message });
  }
}

-1
投票

最好使用asyncawait保持代码干净。您在几种then情况下所做的事情称为callback hell

更好的解决方案可能是下面的一个示例:

exports.updateUserProfile = (req, res) => {
  const userId = req.body.id;
  const password = req.body.password;
  const newIds = req.body.newIds;


  const isValid = await userService.isPasswordValid(userId, password);
  // ... and you can continue using based on this
© www.soinside.com 2019 - 2024. All rights reserved.