Promise属于ES6新加入的语法promise
目前在浏览器中输入Promise就能够看到有这个对象了浏览器
用法是建立一个新的函数来包括原来的函数体而且在原来的函数体中再包一个能够返回一个新的实例化Promise对象而这个promise自带resolve用于回调函数
like this: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内部执行这个函数 }) }
原函数体:spa
function _animate(){ setTimeout(function () { var marginLeft = parseInt(ball.style.marginLeft) if(marginLeft==dis){ resolve() }else{ if(marginLeft<dis){ //dosomething.... } } },13) }
而调用部分code
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的方法(具体内部发生了目前还不了解)对象
使用环境设想:日常会用到比较多的回调函数 这个如何让本身使用回调的更方便blog
resolve()不传入参数是访问不到其余东西的animation
.then 以后的return PromiseAnimate()应该是为了下次的回调因此要return回调函数
留下的问题:这个如何让本身使用回调的更方便?
--------------------
待更新...