promise的使用

  每次打开mdn,就会发现很多神奇的新东西。上百个新的api??这都是些what??。好吧。作为一个前端。一个菜鸟前端。。真的不知道该怎么去学习了。不过饭要一口一口吃。

所以今天就学习下新的promise。。。其实promise的概念已经很久了。jq的ajax的done,fail方法貌似一点几就有了。现在原生的promise来了。那就追赶一下es6的脚步吧。。

   promise的概念已经理解。那么就是实践了。实际上任何方法都可以用promise。比如我要执行一个dom操作。之后再进行另外一个操作。

之前可以这样:

 

<body>
   <a href="javascript:;" id="button">insertDiv</a>
   <div id="div">
   </div>
   <script>
      var div=document.getElementById('div');
      var button=document.getElementById('button');
      function insertSth(sth,fn){
         this.innerHTML=sth;
         fn(sth);
      }
      function showLog(sth){
         console.log('已经插入了'+sth);
      }
      button.addEventListener('click',function(){
         insertSth.call(div,'<a href="javascript:;">我已经插入了</a>',showLog);
      },false);

   </script>
</body>

实现在div中插入了一个a标签。并且打印一个已经插入的提示.

现在有了promise了。就可以这么做:

 

 <script>
      var div=document.getElementById('div');
      var button=document.getElementById('button');
      function insertSth(sth,ele){
         var that=this;
function showLog(sth){
         console.log('已经插入了'+sth);
      }
      button.addEventListener('click',function(){
          insertSth.call(div,'<a href="javascript:;">我已经插入了</a>')
         .then(function(res){
           showLog(res);
         })
      },false);

   </script>

当然要注意promise的this已经指向了window.所以不能在内部直接用this。除非你是想访问全局的数据。当然也可以使用新的箭头函数。不过低版本不支持。改成箭头符号的可以是这样

var promise=new Promise((resolve,reject)=>{
             this.innerHTML=sth;
             resolve(sth);
         });

当然promise还有个catch(),当promise状态为reject就会调用该方法。最重要的是。promise还可以多个then()串起来。而且还有all.race这些好用的api。

posted @ 2017-08-21 11:29  于啊  阅读(187)  评论(0)    收藏  举报