1

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

  • 2
    There doesn't appear to be anything in that code that's async/awaitable _except_ for the promise. – Andy Jul 05 '22 at 04:29
  • 1
    The only asynchronous piece of code here is the `subscribe()` callback. Given event subscriptions don't typically return a promise because they fire more than once, it's unlikely there's anything else you can do with this code – Phil Jul 05 '22 at 04:53
  • 2
    TL;DR you cannot _promisify_ a callback based API without `new Promise()` – Phil Jul 05 '22 at 04:55

1 Answers1

4

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
traktor
  • 17,588
  • 4
  • 32
  • 53
  • 1
    Thank you for clarifying. I was doubted and now I can be sure it's impossible to convert it to no new Promise(). – jasminehuan Jul 05 '22 at 07:04