How to return from a Promise's catch/then block?

前端 未结 3 1637
温柔的废话
温柔的废话 2020-11-30 19:16

There are many tutorials on how to use \"then\" and \"catch\" while programming with JavaScript Promise. However, all these tutorials seem to miss an important point: return

3条回答
  •  清歌不尽
    2020-11-30 19:50

    There is no built-in functionality to skip the entirety of the remaining chain as you're requesting. However, you could imitate this behavior by throwing a certain error through each catch:

    doSomething()
      .then(func1).catch(handleError)
      .then(func2).catch(handleError)
      .then(func3).catch(handleError);
    
    function handleError(reason) {
      if (reason instanceof criticalError) {
        throw reason;
      }
    
      console.info(reason);
    }
    

    If any of the catch blocks caught a criticalError they would skip straight to the end and throw the error. Any other error would be console logged and before continuing to the next .then block.

提交回复
热议问题