富贵资源网 Design By www.hznty.com

js中async函数结合promise的小案例浅析

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
list-style: none;
}
.box{
height: 15px;
margin-top: 20px;
transform: translateX(-100%);
transition: all 1s linear;
}
button{
margin-top: 30px;
}
</style>
</head>
<body>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<button id="btn">点击开始</button>
<script>
const box=document.querySelectorAll(".box")
box.forEach((item,index)=>{
item.style.cssText=`width:${100+index*15}px;background:rgb(${Math.random()*255},${Math.random()*255},${Math.random()*255})`
})
    btn.onclick=async function(){
      for(let i=0;i<box.length;i++){
        await fn(box[i])
      }
    }
    function fn(el){
      return new Promise((resolve,reject)=>{
        el.style.transform=`translateX(0)`;
        el.addEventListener("transitionend",function(){
          resolve();//为什么调用这个成功函数
        })
      })
    }
  </script>
</body>
</html>

富贵资源网 Design By www.hznty.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
富贵资源网 Design By www.hznty.com