三个小球运动:
<!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