ES6promise与ES5回调

2018-01-22

在没有学习promise之前,我们通过ES5语法写一个小练习,需求如下:
1.有三个不同颜色的球,第一个球先向右侧做偏移,到达指定唯一距离后,第二个小球出发,依然向右移动相同的距离,停止后,第三个小球出发,移动到指定距离后,再向左移动一小段距离停止。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
//先获取到三个小球
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回调失败执行的函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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("动画完成");
});

效果如下:
promise效果

all:异步函数同时执行
1
2
3
Promise.all([async1(),async2(),async3()]).catch((err)=>{
console.log(err);
});
race:异步函数,谁执行快,就先执行谁
1
2
3
Promise.race([async1(),async2(),async3()]).catch((err)=>{
console.log(err);
});
ajax请求ES6
1
2
3
4
5
6
7
fetch(url,{option}).then((res)=>{
return res.json();
}).then((res)=>{
console.log(res);
}).catch((err)=>{
console.log(err);
});