1

I am trying to figure out the best way to wait on the results of a subscription where I am passing in a callback. For example let's say I have the following:

function someMethod() {
  let someResult = null;
  someSubPub.subscribe(someTopic, someKey, someValue, (someResponse) => {
     someResult = //do stuff in the callback with someResponse
  });
  return someResult;
}

I'm not quite sure how await would correctly work in this situation, aka blocking inside a callback.

ekjcfn3902039
  • 1,673
  • 3
  • 29
  • 54
  • when you get the result your callback will be called. What do you mean by wait? – Amir Saleem Jul 07 '21 at 16:45
  • I am trying to return someResult from the method. Without blocking somehow, someResult would be null since the subscribe wouldnt happen until some later point. – ekjcfn3902039 Jul 07 '21 at 16:48
  • The sub/pub SDK you're using may already support promises, in which case you can make your function async, return the pub/sub promise, and await the result. – jarmod Jul 07 '21 at 16:50

1 Answers1

4

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?

alexanderbird
  • 3,847
  • 1
  • 26
  • 35