看例子就行了,廢話不多說!
async function checkStatus(name){
return new Promise((resolve,reject) => {
var that = this;
this.timer = setTimeout(()=>{
// clearTimeout(that.timer); -- todo 這里取消注釋會有問題,難道timer沖突了?
if(name === "success") resolve(true);
else reject(false);
},500);
});
}
async function doSth(){
/*
正常使用的時候 :
可以用then來接收resolve的結果;
使用catch接受reject的結果
*/
console.log('===== 使用Promise.then 接收resolve返回的結果 =====');
var ret_s = checkStatus('success');
ret_s.then(res => console.log('use Promise.then() , return :' ,res) );
console.log('===== 使用Promise.catch 接收reject返回的結果 =====');
var ret_err = checkStatus('ss');
ret_err.catch(res => console.log('use Promise.catch() , return :',res));
console.log('\r\n');
/*
使用await 的時候:
不需要使用then來接收resolve的結果,直接就得到了結果
對於reject的結果,采取靜默處理. 只能通過try-catch來捕獲
和Promise的另外一個不同是,下面這兩個調用是串行的,而不是像上面兩個例子是並行的.
*/
console.log('===== 使用Promise.then 接收resolve返回的結果 =====');
var res_s = await checkStatus('success');
console.log("await success result :",res_s);
console.log('===== 使用await 接收reject返回的結果 =====');
try{
await checkStatus('fail');
}catch(res_err){
console.log('await handle the reject result :',res_err);
}
}
doSth();