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