将新的承诺转换为模态方法的异步/等待

发布于 2025-02-13 04:18:19 字数 46 浏览 0 评论 0 原文

我试图将这些代码转换为异步/等待。但是看来这是不可能的!!!有人有任何建议吗?

I have tried to convert these pieces of code to async/await. But seem it is impossible!!! Does anyone have any suggestions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

陌路终见情 2025-02-20 04:18:19

正如评论中已经提到的那样,您无法等待在没有创造新承诺的情况下无法提供承诺接口的事件。但是,您可以在Promise Executor函数之外承诺触发事件和过程 popupdata.data 等待操作员仍需要在 async函数或JavaScript模块

Vanilla JS中的示例:

async methodName() {
  if (this.notificationPopupSubscription) this.notificationPopupSubscription.unsubscribe();

  const popup = await new Promise(resolve => {
    this.notificationPopupSubscription = modal.onAnyCloseEventFinished.subscribe(resolve);
  });
  const popupData = popup.getData();
  popup.removeData();
  if (!popupData.data) {
    throw Error("no data"); // reject promise returned by async method
  }
  return popupData.data;  // fulfill promise ...
}

在示例中, this.notificationpopupsubscription 是在执行程序中同步设置的,但是在等待已解决的承诺后,弹出变量是设置的。当然,仍然需要使用适当的值来调用封闭功能/类方法。

As already mentioned in comment, you can't await events that don't supply a promise interface without creating a new promise. You could, however, promisify firing of the event and process popupData.data outside of the promise executor function. The await operator will still need to be used in an async function or JavaScript module

Example in vanilla JS:

async methodName() {
  if (this.notificationPopupSubscription) this.notificationPopupSubscription.unsubscribe();

  const popup = await new Promise(resolve => {
    this.notificationPopupSubscription = modal.onAnyCloseEventFinished.subscribe(resolve);
  });
  const popupData = popup.getData();
  popup.removeData();
  if (!popupData.data) {
    throw Error("no data"); // reject promise returned by async method
  }
  return popupData.data;  // fulfill promise ...
}

In the example, this.notificationPopupSubscription is set synchronously in the executor, but the popup variable is set after waiting for the promise to be resolved. The enclosing function/class method still needs to be called with an appropriate this value of course.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文