What we Think , latest news

Promise回调地狱学习小小小小小笔记

Promise属于ES6新加入的语法

目前在浏览器中输入Promise就可以看到有这个对象了

用法是创建一个新的函数来包括原来的函数体并且在原来的函数体中再包一个可以返回一个新的实例化Promise对象而这个promise自带resolve用于回调

like this:

    function promiseAnimate(ball,dis){
        return new Promise(function(resolve,reject){
            function _animation() {
                setTimeout(function () {
                    var marginLeft = parseInt(ball.style.marginLeft);
                    if (marginLeft == dis) {
                        resolve()
                    } else {
                        if (marginLeft < dis) {
                            marginLeft++
                        } else {
                            marginLeft--
                        }
                        ball.style.marginLeft = marginLeft + 'px'
                        _animation();
                    }
                }, 13)
            }
            _animation();//由于被包裹进去之后无法进行加载那个方法所以要在函数的Promise内部执行这个函数
        })
    }

原函数体:

    function _animate(){
        setTimeout(function () {
            var marginLeft = parseInt(ball.style.marginLeft)
            if(marginLeft==dis){
                resolve()
            }else{
                if(marginLeft<dis){
            //dosomething....
                }
            }
        },13)
    }

而调用部分

    promiseAnimate(ball1,100)
        .then(function(){
              return promiseAnimate(ball2,200)
        })
        .then(function(){
            return promiseAnimate(ball3,300)
        })
        .then(function(){
            return promiseAnimate(ball3,100)
        })
        .then(function(){
            return promiseAnimate(ball2,100)
        })
        .then(function(){
            return promiseAnimate(ball1,100)
        })

首先是第一次开始调用这个函数,由于有resolve(详细的原理还不清楚)在执行完以上的就会符合条件进行resolve(),由于之前在最外层的函数(promiseAnimate)内返回了一个实例化了的promise对象所以这个对象就有了then的方法(具体内部发生了目前还不了解)

使用环境设想:平常会用到比较多的回调函数 这个如何让自己使用回调的更方便

resolve()不传入参数是访问不到其他东西的

.then 之后的return PromiseAnimate()应该是为了下次的回调所以要return

留下的问题:这个如何让自己使用回调的更方便?

 --------------------

待更新...

 

posted @ 2017-07-02 21:16  sakura丶shadow  阅读(235)  评论(0编辑  收藏  举报