• 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(); 
  • 相关阅读:
    python 二维数组遍历
    WINFORM中treeview 节点显示不全
    C++函数式编程实现牛顿法
    C++函数式编程
    C++函数的重载
    默认形参值
    常量指针和指针常量
    C++值传递与引用传递
    C++变量和基本类型——2.3.1引用
    C++ 实参和形参
  • 原文地址:https://www.cnblogs.com/lmxxlm-123/p/11131898.html
Copyright © 2020-2023  润新知