Async/Await are nice, but sometimes it's simpler to think about the Promise
construct that async
/await
abstracts away.
I suggest:
function someMethod() {
return new Promise((resolve, reject) => {
someSubPub.subscribe(someTopic, someKey, someValue, () => {
const someResult = //do stuff in the callback
resolve(someResult);
});
});
}
If you don't want to work with promises directly, you can wrap someSubPub.subscribe
to return a promise
function someSubPubSubscribePromise(topic, key, value) {
return new Promise((resolve, reject) => {
someSubPub.subscribe(topic, key, value, resolve);
});
}
async function someMethod() {
await someSubPubSubscribePromise(someTopic, someKey, someValue);
const someResult = //do stuff in the callback
return someResult;
}
In either of those examples, you can do const result = await someMethod()
(you can await
both async
methods and regular methods that return a promise)
One thing to consider: usually a pub/sub interface can call the callback multiple times. An async method / a method returning a promise can only resolve or reject exactly once. Probably you should be unsubscribing in the callback after you've responded to the event once?