Promise 与 await 组合使用


看例子就行了,废话不多说!
 
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(); 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM