Promise

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           //既然是承诺 , 不会马上执行

回调动画演示





    
    
    
    Document
    



     
    

改成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)
        })

你可能感兴趣的:(Promise)