correct way to handle errors inside a Promise

前端 未结 3 2041
无人共我
无人共我 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 17:02

    You are throwing an error in an asynchronous function, instead of rejecting the promise.

    Change throw Error("") to reject(""):

    promiseFunc()
      .then(result => {
        console.info(`.THEN:: ${result}`)
      })
      .catch(error => {
        console.info(`.CATCH:: ${error}`)
      })
    
    function promiseFunc() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          reject("setTimeout's callback error")
          resolve('resolution')
        }, 1000)
      })
    }
    

    Or add a try-catch statement, and reject it in the catch block

    setTimeout(() => {
      try {
        throw new Error("setTimeout's callback error")
      } catch(error) {
        reject(error)
      }
      resolve('resolution')
    }, 1000)
    

提交回复
热议问题