0

I'm using Express to build a REST API with Objection.js ORM. One of my controller's method has a chain of Promises:

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.');
      }
    );
}

When an exception is caught on the first .catch() block, it returns the response with an error, but the chain keeps executing, and even if I don't return anything in the 1st catch block, the chain continues to the next .then().

Is this the expected behavior? If so, how can I "break the chain" or something like that.

SiddAjmera
  • 38,129
  • 5
  • 72
  • 110
  • 1
    Yes, this is expected. `return` doesn't break out of a promise chain, it just finishes the current callback. – Bergi Oct 05 '18 at 14:12
  • Adding to @Bergi's comments, don't return anything from `catch` to break the chain. Also, a cleaner way of implementing this would be by using `async`/`await` syntax. – SiddAjmera Oct 05 '18 at 14:15
  • @SiddAjmera does `async`/`await` hits the performance? one of the reasons I wasn't using it, it's because i really need performance on this project – Gabriel Bitencourt Oct 05 '18 at 14:22
  • @GabrielBitencourt, [This Article](https://dzone.com/articles/javascript-promises-and-why-asyncawait-wins-the-ba) says otherwise – SiddAjmera Oct 05 '18 at 14:24
  • well, awesome, @SiddAjmera. Thanks! – Gabriel Bitencourt Oct 05 '18 at 14:36

0 Answers0