前端開發中會遇到不少異步回到,和相互依賴關係的狀況,下面咱們就經過一個簡單案例總體的瞭解一下,經常使用的異步回調的用法和優點
1.案例很簡單,頁面上有三個小球
2.當頁面加載後,第一個小球會向左滾動,當第一個小球到達500px的位置,第二個小球開始運動,當第二個小球到達300px的位置時,第三個小球開始運動,也一樣向左滾動100px,當第三個小球到達位置時,瀏覽器彈出‘ok’
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{
padding: 0;
margin: 0;
}
#box{
position: absolute;
}
#box div{
width: 100px;
height: 100px;
background: red;
position: absolute;
left: 0;
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
border-radius: 50%;
}
#box :nth-child(1){
top: 0;
}
#box :nth-child(2){
top: 120px;
}
#box :nth-child(3){
top: 240px;
}
</style>
</head>
<body>
<div id="box">
<div></div>
<div></div>
<div></div>
</div>
</body>
</html>
callback 方法
- callback 寫發就出現了你們常見的回調地獄(倒金字塔)結構的代碼
<script>
let box = document.getElementById('box');
let balls = box.querySelectorAll('div');
function run(ele,speed,callback){
let pos = 0;
let timer = setInterval(()=>{
pos+=2;
if(pos>=speed){
clearInterval(timer);
callback();
}else{
ele.style.left = pos +'px';
}
},10)
}
run(balls[0],500,function(){
run(balls[1],300,function(){
run(balls[2],100,function(){
alert('ok')
})
})
})
</script>
Pormise 方法
- 經過使用Promise的then方法,一樣達到了效果,而且解決了,回到地獄問題;
<script>
let box = document.getElementById('box')
let balls = box.querySelectorAll('div')
function run(ele,speed){
return new Promise((resolve,reject)=>{
let pos = 0;
let timer = setInterval(()=>{
pos+=2;
if(pos>=speed){
clearInterval(timer);
resolve();
}else{
ele.style.left = pos +'px';
}
},10)
})
}
run(balls[0],500).then(data=>{
return run(balls[1],300);
}).then(data=>{
return run(balls[2],100);
}).then(data=>{
alert('ok');
})
</script>
async await 方法
<script>
let box = document.getElementById('box')
let balls = box.querySelectorAll('div')
function run(ele,speed){
return new Promise((resolve,reject)=>{
let pos = 0;
let timer = setInterval(()=>{
pos+=2;
if(pos>=speed){
clearInterval(timer);
resolve();
}else{
ele.style.left = pos +'px';
}
},10)
})
}
async function m(){
await run(balls[0], 500);
await run(balls[1], 300);
await run(balls[2], 100);
}
m().then(data=>{
alert('ok')
})
</script>