js中async函数结合promise的小案例浅析
程序员文章站
2022-03-23 12:56:31
<!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>