一、resolve
当a>0时,正常情况依次输出A、B、C
console.log("A");
let result = await this.test();
console.log("C:",result); private test(){
return new Promise((resolve,reject)=>{
console.log("B");
let a = 3;
if(a > 0){
resolve(a);
}else{
reject(0);
}
});
}
二、没有处理失败信息,导致程序无法继续执行
当a<0时。输出A、B后,C无法输出,程序无法继续往下执行。
console.log("A");
let result = await this.test();
console.log("C:",result); private test(){
return new Promise((resolve,reject)=>{
console.log("B");
let a = -3;
if(a > 0){
resolve(a);
}else{
reject(0);
}
});
}
三、catch
增加catch处理错误,程序可以继续执行
console.log("A");
let result = await this.test();
console.log("C:",result); private test(){
return new Promise((resolve,reject)=>{
console.log("B");
let a = -3;
if(a > 0){
resolve(a);
}else{
reject(0);
}
}).catch((err)=>{
console.log("err:", err);
});
}
这样也可以
let result = await this.test().catch(()=>{});
四、使用then处理错误,程序继续执行
换一种写法,使用then。
console.log("A");
let result = await this.test().then((res)=>{
console.log("success:", res);
},(res)=>{
console.log("fail:", res);
});
console.log("C:",result); private test(){
return new Promise((resolve,reject)=>{
console.log("B");
let a = -3;
if(a > 0){
resolve(a);
}else{
reject(0);
}
});
}
五、在await处使用catch,程序继续执行
protected async createGameScene() {
console.log("A");
let result = await this.test().catch((err)=>{console.log("err:",err)});
console.log("C:",result);
} private test(){
return new Promise((resolve,reject)=>{
console.log("B");
let a = -3;
if(a > 0){
resolve(a);
}else{
reject(0);
}
});
}
六、在test里catch后,程序会不执行then的reject,而是resolve。
protected async createGameScene() {
console.log("A");
let result = await this.test().then((res)=>{
console.log("C:",res);
},(res)=>{
console.log("D:",res)
}).catch((err)=>{console.log("E:",err)});
console.log("F:",result);
} private test(){
return new Promise((resolve,reject)=>{
console.log("B");
let a = -3;
if(a > 0){
resolve(a);
}else{
reject(0);
}
}).catch((err)=>{console.log("test err:", err)});
}