Jay*_*oto 1 javascript css async-await
我需要一个在转换完成时返回承诺的元素。下面的代码工作正常,但是,我想知道是否可以用完整的async/await语法重写此代码。
const box = document.querySelector(".box");
const animate = () =>
new Promise((resolve) => {
box.classList.add("animate");
box.addEventListener("transitionend", () => resolve());
});
box.addEventListener(
"click",
async() => {
await animate();
console.log("done animating!");
}, {
once: true
}
);Run Code Online (Sandbox Code Playgroud)
.box {
width: 100px;
height: 100px;
background-color: blue;
transition: width 3s linear;
}
.box.animate {
width: 100%;
}Run Code Online (Sandbox Code Playgroud)
<div class="box"></div>Run Code Online (Sandbox Code Playgroud)
async并且await是管理现有承诺的工具。
它们替换 using then()(并替换catch()为常规try/catch)。
他们无法将使用回调的 API 转换为返回承诺的 API。您仍然需要为此使用 Promise 构造函数。