window.Promise Demo

三个小球运动:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
    .ball{
      width: 20px;
      height: 20px;
      border-radius: 50%;
      background: pink;
    }
    .ball2{
      background: red;
    }
    .ball3 {
      background: gold;
    }
  </style>
</head>
<body>
<div class="ball ball1" style="margin-left: 0;"></div>
<div class="ball ball2" style="margin-left: 0;"></div>
<div class="ball ball3" style="margin-left: 0;"></div>

<script src='http://res.cloudinary.com/moveha/raw/upload/v1438413173/dist/lib/bluebird-2.9.34/bluebird.min.js'></script>
<script>
  var ball1 = document.querySelector('.ball1')
  var ball2 = document.querySelector('.ball2')
  var ball3 = document.querySelector('.ball3')
  var Promise = window.Promise

  function promiseAnimate(ball, distance) {
    return new Promise(function(resolve, reject) {
      function _animation() {
        setTimeout(function() {
          var marginLeft = parseInt(ball.style.marginLeft, 10)
          if (marginLeft === distance) {
            resolve()
          }
          else {
            if (marginLeft < distance) {
              marginLeft++
            }
            else {
              marginLeft--
            }
            ball.style.marginLeft = marginLeft + 'px'
            _animation()
          }
        }, 14)
      }
      _animation()
    })
  }
  promiseAnimate(ball1, 60)
    .then(function() {
      return promiseAnimate(ball2, 150)
    })
    .then(function() {
      return promiseAnimate(ball3, 250)
    })
    .then(function() {
      return promiseAnimate(ball3, 120)
    })
    .then(function() {
      return promiseAnimate(ball2, 120)
    })
    .then(function() {
      return promiseAnimate(ball1, 120)
    })
</script>

</body>
</html>

  • 一个promise可能有三种状态:等待(pending)、已完成(fulfilled)、已拒绝(rejected)
  • 一个promise的状态只可能从“等待”转到“完成”态或者“拒绝”态,不能逆向转换,同时“完成”态和“拒绝”态不能相互转换
  • promise必须实现then方法(可以说,then就是promise的核心),而且then必须返回一个promise,同一个promise的then可以调用多次,并且回调的执行顺序跟它们被定义时的顺序一致
  • then方法接受两个参数,第一个参数是成功时的回调,在promise由“等待”态转换到“完成”态时调用,另一个是失败时的回调,在promise由“等待”态转换到“拒绝”态时调用。同时,then可以接受另一个promise传入,也接受一个“类then”的对象或方法,即thenable对象。
promise也是CommonJS规范的一部分
网上经典讲解:http://blog.youkuaiyun.com/u014267351/article/details/51236549

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值