Skipping promise chain after handling error

后端 未结 3 675
星月不相逢
星月不相逢 2021-01-02 11:06

Using the https://github.com/kriskowal/q library, I\'m wondering if it\'s possible to do something like this:

// Module A

function moduleA_exportedFunction(         


        
3条回答
  •  攒了一身酷
    2021-01-02 12:02

    Inspired by Benjamin Gruenbaum's comments and answer - if I was writing this in synchronous code, I would make moduleA_exportedFunction return a shouldContinue boolean.

    So with promises, it would basically be something like this (disclaimer: this is psuedo-code-ish and untested)

    // Module A
    
    function moduleA_exportedFunction() {
      return promiseReturningService().then(function(serviceResults) {
        if (serviceResults.areGood) {
          // We can continue with the rest of the promise chain
          return true;
        }
        else {
          performVerySpecificErrorHandling();
          // We want to skip the rest of the promise chain
          return false;
        }
      });
    }
    
    // Module B
    
    moduleA_exportedFunction()
      .then(function(shouldContinue) {
        if (shouldContinue) {
          return moduleB_promiseReturningFunction().then(moduleB_anotherFunction);
        }
      })
      .fail(function(reason) {
        // Handle the reason in a general way which is ok for module B functions
        // (And anything unhandled from module A would still get caught here)
      })
      .done()
    ;
    

    It does require some handling code in module B, but the logic is neither specific to module A's internals nor does it involve throwing and ignoring fake errors - mission accomplished! :)

提交回复
热议问题