0

I am performing multiple ajax calls, and I want to complete all of them before I display my form. If there is an error, I want to stop processing and just show the first error encountered. I have googled a lot of articles, including on StackOverflow, that show how to chain the then statements. But it appears I have to attach a catch to each then, otherwise only errors in the last statement are caught. In this example, Lookup is an async call which returns a promise, and ShowError handles the error:

Data.Lookup("a")
  .then(function(result) {
    vm.a = result;
    Data.Lookup("b")
      .then(function(result) {
        vm.b = result;
        Data.Lookup("c")
          .then(function(result) {
            vm.c = result;
          })
          .catch(function(response) {
            vm.showError(response);
          });
      })
      .catch(function(response) {
        vm.showError(response);
      });
  })
  .catch(function(response) {
    vm.showError(response);
  });

Assuming there is at least one error, is there any way to use a single catch, that will trigger when the FIRST error is encountered?

This is a different requirement than the question Wait for all promises to resolve. As stated in the title, that user wants to process ALL promises. I am happy to quit when after the FIRST promise that has an error.

CigarDoug
  • 1,438
  • 1
  • 15
  • 29
  • Possible duplicate of [Wait for all promises to resolve](https://stackoverflow.com/questions/21759361/wait-for-all-promises-to-resolve) – Protozoid Jun 05 '18 at 19:55
  • The difference is, I want to quit when the first error occurs. I don't need to wait for all of the promises to be processed. – CigarDoug Jun 05 '18 at 20:18

1 Answers1

2

Add return, so result promise fails if one of inner fail:

Data.Lookup("a")
  .then(function(result) {
    vm.a = result;
    return Data.Lookup("b")
      .then(function(result) {
        vm.b = result;
        return Data.Lookup("c")
          .then(function(result) {
            vm.c = result;
          });
      });
  })
  .catch(function(response) {
    vm.showError(response);
  });
Petr Averyanov
  • 9,327
  • 3
  • 20
  • 38