Strange Unhandled promise rejection

the following code always outputs Unhandled promise rejection (rejection id: 1): error1 , how to avoid it?

the main function is that getVal preloads the first call, waits without return on the second call, and takes the value directly when it is returned

const rejects = [0,1]
let i = 0
function getSummary( id) {
  return new Promise((resolve, reject) => {
    console.log("rr", id, i)
    if(rejects.includes(i)) {
      setTimeout(() => reject("error1"), 200)
    } else if(id === 1) {
      setTimeout(() => resolve(id), 200)
    } else {
      setTimeout(() => resolve(id), 500)
    }
    iPP
  })
}

class Test {
  test() {
    this.getVal()

    setTimeout(async () => {
      try {
      const val = await this.getVal()
      console.log("get1", val)
      }catch (ex) {
        console.log("error")
      }
      console.log("get2", await this.getVal())
    }, 1000)
  }
  async getVal() {
    try {
      if (!this.summary) {
        this.summary = getSummary(1).catch(() => getSummary(2)).then((data) => {
          this.summary = data
          return data
        })
      } else if(this.summary.then) {
        return await this.summary
      }
    } catch (ex) {
      this.summary = null
    }
    return this.summary
  }
}
new Test().test()
< hr >

has been resolved see floor 3
as mentioned on floor 1, the first getVal exception is thrown up, and try catch is not allowed, only Await.
had to go to see the await changed to the third floor


when the state of Promise changes to rejection , it is not handled correctly, leaving the (propagation), bubbling until it is captured by the process. This Promise is called unhandled promise rejection .

//  .then(undefined, () => {})
new Promise((resolve, reject) => {
  // ...
  reject('timeout');
}).then(undefined, (error) => {
  console.error(error);
});

//  .catch(() => {})
new Promise((resolve, reject) => {
  // ...
  reject('timeout')
}).catch((error) => {
  console.error(error);
})

the key point is not to let the exception be thrown.


Is that what

means

  

Unhandled promise rejection SyntaxError: syntax errors are reported in IE9 and IE10. How to solve them?

Menu