correct way to handle errors inside a Promise

前端 未结 3 2062
无人共我
无人共我 2021-01-13 16:06

Currently, I\'m trying to decide what pattern I should use while dealing with errors inside a Promise. For instance, I have the code below

promiseFunc()
.the         


        
3条回答
  •  甜味超标
    2021-01-13 16:46

    Resolve, Reject and Error are three distinct things and your code need to handle cases when you need to resolve and when you need to reject it. If the condition you want is full-filled then you call the resolve method, with the condition can't be full-filled then call the reject() method.

    In case of any errors thrown by your code or any other reason the single catch() block in the end of chain would be executed.

    // doAsyncOperation1() returns a promise.
    doAsyncOperation1()
    .then(() => {
      // ...
      // doAnotherAsyncOperation() returns a promise
      // which will be inserted into the chain.
      return doAsyncOperation2();
    })
    .then((output) => {
      // output will be the value resolved by the
      // promise which was returned from doAsyncOperation2()
      // ...
      return doAsyncOperation3();
    })
    .catch((err) => {
      // Handle any error that occurred in any of the previous
      // promises in the chain.
    });
    

提交回复
热议问题