承诺链不会在异常捕获后返回时中止

时间:2018-10-05 14:06:53

标签: node.js promise objection.js

我正在使用Express通过Objection.js ORM构建REST API。我的控制器的一种方法具有一连串的承诺:

register(req, res) {
  // ...
  indicative.validateAll(req.body.data, rules)
    .then(
      () => {
        const data = {
          ...req.body.data,
          password: bcrypt.hashSync(req.body.data.password, bcrypt.genSaltSync()),
          password_confirmation: undefined,
          customer: {}
        };
        return models.User.query()
          .insertGraph(data);
      }
    )
    .catch( // catch block 1
      (error) => {
        console.log(error);
        return response.error(res, 422, 'Dados de cadastro inválidos.');
      }
    )
    .then(
      (user) => {
        return response.success(res, 'Usuário cadastrado com sucesso.', {
          user: user
        });
      }
    )
    .catch( // catch block 2
      (error) => {
        console.log(error);
        return response.error(res, 500, 'Erro interno, tente novamente.');
      }
    );
}

当在第一个.catch()块上捕获到异常时,它返回带有错误的响应,但是链会继续执行,即使我在第一个catch块中未返回任何内容,链也会继续到下一个.then()

这是预期的行为吗?如果是这样,我该如何“打破连锁”或类似的事情。

0 个答案:

没有答案