
async await 中退出不确定时间的回调函数
在使用 async await 时,如果需要在不确定时间的回调函数中退出,可以通过 promise.withresolvers() 接口实现。
修改代码
将 b 函数修改为:
const b = async (): Promise<void> => {
const { promise, resolve } = Promise.withResolvers<void>();
const callback = (mutations: MutationRecord[]) => {
resolve();
};
const observer = new MutationObserver(callback);
observer.observe(buttonEl, {
attributes: true,
});
await p();
buttonEl.click();
// 下面这句也可以用 return promise,取决于你的后续逻辑
await promise;
};原理
promise.withresolvers() 返回一个 promise 和解决器对象。将其应用于此场景:
考虑因素
以上就是如何优雅地使用 async/await 退出不确定时间的回调函数?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号