天天看点

html5 promise的使用

promise的目的是减少callback的嵌套,提高代码的可维护性。看一个抽奖的例子,每次抽奖要1秒,共5次,生成一个1-10随机数,大于5则中奖。

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html;charset=utf-8">
  <title></title>
</head>
<body>
  <script>
    function drawPrize(){
      var defer = Promise.defer()
      setTimeout(function(){
        var random = parseInt(Math.random() * 10);
        if(random>5){
          defer.resolve({msg: 'gt 5', score: random});
        }else{
          defer.reject({msg: 'lte 5', score: random});
        }
      },1000);
      return defer.promise;
    }
    for(var i=1;i<6;i++){
      // drawPrize().then(function(data){
      //   console.log(data);
      //   console.log('您中奖了');
      // }).catch(function(data){
      //   console.log(data);
      //   console.log('您未中奖');
      // });
      drawPrize().then(function(data){
        console.log(data);
        console.log('您中奖了');
      },function(data){
        console.log(data);
        console.log('您未中奖');
      });
    }
  </script>
</body>
</html>
           

处理失败既可以放在catch中,也可以放在then的第二个参数。

Promise.defer()这种写法已经被一些新浏览器废弃,应使用new Promise()创建。

新代码:

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html;charset=utf-8">
  <title></title>
</head>
<body>

  <script>
    function drawPrize(){
      return new Promise(function(resolve,reject){
        setTimeout(function(){
          var random = parseInt(Math.random() * 10);
          if(random>5){
            resolve({msg: 'gt 5', score: random});
          }else{
            reject({msg: 'lte 5', score: random});
          }
        },1000);
      });
    }
    for(var i=1;i<6;i++){
      // drawPrize().then(function(data){
      //   console.log(data);
      //   console.log('您中奖了');
      // }).catch(function(data){
      //   console.log(data);
      //   console.log('您未中奖');
      // });
      drawPrize().then(function(data){
        console.log(data);
        console.log('您中奖了');
      },function(data){
        console.log(data);
        console.log('您未中奖');
      });
    }
  </script>
</body>
</html>
           

继续阅读