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(); 
  • 相关阅读:
    HDU 1560 DNA sequence (迭代加深搜索)
    POJ-1077 HDU 1043 HDU 3567 Eight (BFS预处理+康拓展开)
    CSUST 1011 神秘群岛 (Dijkstra+LCA)
    LCA 倍增
    HDU 1003 Max Sum 求区间最大值 (尺取法)
    Codeforce 867 C. Ordering Pizza (思维题)
    POJ 3349 Snowflake Snow Snowflakes (Hash)
    POJ 2774 Long Long Message (Hash + 二分)
    POJ 1200 Crazy Search (Hash)
    前端面试总结(转)
  • 原文地址:https://www.cnblogs.com/lmxxlm-123/p/11131898.html
Copyright © 2011-2022 走看看