我需要一个在转换完成时返回 promise 的元素。下面的代码工作正常,但是,我想知道是否可以用完整的 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
}
);
.box {
width: 100px;
height: 100px;
background-color: blue;
transition: width 3s linear;
}
.box.animate {
width: 100%;
}
<div class="box"></div>
答案 0 :(得分:5)
async
和 await
是管理现有承诺的工具。
它们使用 then()
替换(并将 catch()
替换为常规的 try/catch
)。
他们无法将使用回调的 API 转换为返回承诺的 API。您仍然需要为此使用 Promise 构造函数。