I have tried to convert these pieces of code to async/await. But seem it is impossible!!! Does anyone have any suggestions?
Asked
Active
Viewed 223 times
1
-
2There doesn't appear to be anything in that code that's async/awaitable _except_ for the promise. – Andy Jul 05 '22 at 04:29
-
1The 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
-
2TL;DR you cannot _promisify_ a callback based API without `new Promise()` – Phil Jul 05 '22 at 04:55
1 Answers
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.
-
1Thank 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