zoukankan      html  css  js  c++  java
  • 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(' ');
     
      /*
        使用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(); 
  • 相关阅读:
    最简单的jQuery插件
    SQL执行时间
    Resharper 8.2 注册码
    Module模式
    RestSharp使用
    使用MVC过滤器保存操作日志
    Ajax Post 类实例
    IBatis分页显示
    IBatis插入类的实例
    Topcoder SRM629 DIV2 解题报告
  • 原文地址:https://www.cnblogs.com/lmxxlm-123/p/11131898.html
Copyright © 2011-2022 走看看