可以将此代码重写为异步函数吗?

我需要一个在转换完成时返回承诺的元素。下面的代码工作正常,但是,我想知道是否可以用完整的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></div>

回答

async并且await管理现有承诺的工具。

它们替换 using then()(并替换catch()为常规try/catch)。

他们无法将使用回调的 API 转换为返回承诺的 API。您仍然需要为此使用 Promise 构造函数。


以上是可以将此代码重写为异步函数吗?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>