在没有学习
promise
之前,我们通过ES5语法写一个小练习,需求如下:
1.有三个不同颜色的球,第一个球先向右侧做偏移,到达指定唯一距离后,第二个小球出发,依然向右移动相同的距离,停止后,第三个小球出发,移动到指定距离后,再向左移动一小段距离停止。
1234567891011121314151617181920212223242526272829303132333435 //先获取到三个小球var balls=document.getElementsByClassName("ball");function move(obj,dis,fn){var x=obj.style.marginLeft;if(x==""){x=0;}x=parseInt(x);if(x<dis){setTimeout(function(){x++;obj.style.marginLeft=x+"px";move(obj,dis,fn);},10);}else if(x>dis){setTimeout(function(){x--;obj.style.marginLeft=x+"px";move(obj,dis,fn);});}else{fn && fn();}}//调用(回调)move(balls[0],300,function(){move(balls[1],300,function(){move(balls[2],300,function(){move(balls[2],150,function(){console.log("动画完成");});});});});
效果如图:
我们可以看到ES5里的回调显得代码体态臃肿,ES6里的
promise
类就没有这种问题,异步执行,还能做错误返回resolve
回调成功执行的函数reject
回调失败执行的函数
1234567891011121314151617181920 function test(){return new Promise(function(resolve,reject){var num=parseInt(Math.random()*10);setTimeout(function(){if(num>5){console.log("成功了回调");resolve();}else{reject("回调出了问题");}},500);});}//调用test().then(function(){console.log("test里的函数");}).catch(function(reason){//回调失败console.log(reason);});小球的promise
12345678910111213141516171819202122232425262728293031323334353637 function async(obj,dis){return new Promise(function(resolve,reject){function move(obj,dis){var x=obj.style.marginLeft;if(x=""){x=0;}x=parseInt(x);if(x<dis){setTimeout(function(){x++;obj.style.marginLeft=x+"px";move(obj,dis);},10);}else if(x>dis){setTimeout(function(){x--;obj.style.marginLeft=x+"px";move(obj,dis);});}else{resolve();}}move(obj,dis);});}//调用async(balls[0],300).then(function(){return async(balls[1],300);}).then(function(){return async(balls[2],300);}).then(function(){return async(balls[2],150);})then(function(){console.log("动画完成");});
效果如下:
all:异步函数同时执行
|
|
race:异步函数,谁执行快,就先执行谁
|
|
ajax请求ES6
|
|