Promise它是JS内置的
写AJAX嵌套的时候,可能会陷入不停回调 . 解决方法就是 尝试把他们拆开
Promise
return new Promise(function(resolve,reject ){}){}
例子
var promise = $.ajax({
url:'./user.json',
method:'get'
})
promise.then() //promise的API then接受两个参数 ,第一个成功会怎么样 , 第二个如果失败会怎么样 。
之后还可以再then
- 第一次then有两个参数,第二次then只走resolve
- 第一次then只有resolve,如果第一次失败,第二次then不会执行
var a = new Promise(function(resolve,reject){
resolve()
})
a.then(function(){console.log(1)})
console.log(2)
//2
//1 //既然是承诺 , 不会马上执行
回调动画演示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.ball {
width: 40px;
height: 40px;
border-radius: 20px;
}
.ball1 {
background: red;
}
.ball2 {
background: yellow;
}
.ball3 {
background: green;
}
</style>
</head>
<body>
<!--js的element.style.attribute,只能获取内联样式,所以要加上style-->
<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>
var ball1 = document.querySelector('.ball1')
var ball2 = document.querySelector('.ball2')
var ball3 = document.querySelector('.ball3')
function animate(ball, distance, callback) {
setTimeout(function () {
var marginLeft = parseInt(ball.style.marginLeft, 10)
if (marginLeft === distance) {
callback && callback()
} else {
if (marginLeft < distance) {
marginLeft++
} else {
marginLeft--
}
ball.style.marginLeft = marginLeft + 'px'
animate(ball, distance, callback)
}
}, 13);
}
animate(ball1, 100, function () {
animate(ball2, 200, function () {
animate(ball3, 300, function () {
animate(ball3, 150, function () {
animate(ball2, 150, function () {
animate(ball1, 150, function () {
})
})
})
})
})
})
</script>
</body>
</html>
改成promise
function prommiseAnimate(ball, distance) {
return new Promise((resolve, reject) => {
function _animate() {
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'
_animate()
}
}, 13);
}
_animate()
})
}
prommiseAnimate(ball1, 100).then(() => {
return prommiseAnimate(ball2, 200)
}).then(() => {
return prommiseAnimate(ball3, 300)
}).then(() => {
return prommiseAnimate(ball3, 150)
}).then(() => {
return prommiseAnimate(ball2, 150)
}).then(() => {
return prommiseAnimate(ball1, 150)
})