Correct use of Meteor.wrapAsync() on EventEmitter

Apparently, I am doing something wrong here, since the log tells me that ldapGetResult2 is output before ldapGetResult1:

  /**
   * Get the search result from a LDAP search.
   *
   * @param  {Object} search Event emitter.
   * @throws {Error}         if getting result fails.
   * @return {Object}        Object with search results.
   */
  const ldapGetResult = (search) => {
    const resultGet = Meteor.wrapAsync(search.on, search);

    try {
      let res;

      resultGet('searchEntry', (entry) => {
        res = entry.object;
        console.log('ldapGetResult1', JSON.stringify(res));
      });

      console.log('ldapGetResult2', JSON.stringify(res));

      return res;
    } catch (getErr) {
      throw new Error(`get result failed: ${getErr}`);
    }
  };

So, how can I make this method wait for the result and then return these?

And of cause ldapGetResult1 does show the expected results, while ldapGetResult2 is undefined…

I’m guessing that the use of a callback tells the function to run async.

Try calling resultGet synchronously:

  const ldapGetResult = (search) => {
    const resultGet = Meteor.wrapAsync(search.on, search);

    try {
      let res;

      const entry = resultGet('searchEntry');
      res = entry.object;
      console.log('ldapGetResult1', JSON.stringify(res));

      console.log('ldapGetResult2', JSON.stringify(res));

      return res;
    } catch (getErr) {
      throw new Error(`get result failed: ${getErr}`);
    }
  };

Yes, of cause, however, now I get an error:

I20190104-09:37:10.018(1)?   _maxListeners: undefined }
W20190104-09:37:10.045(1)? (STDERR) (node:92454) UnhandledPromiseRejectionWarning: TypeError: Converting circular structure to JSON
W20190104-09:37:10.046(1)? (STDERR)     at JSON.stringify (<anonymous>)
W20190104-09:37:10.046(1)? (STDERR)     at Object.DDPCommon.stringifyDDP (packages/ddp-common/utils.js:116:15)
...

And I see that comes from the

const entry = resultGet('searchEntry');

So that indicates to me that there is a JSON.stringify() call somewhere in Meteor.wrapAsync() which don’t like that circular structure of the resulting entry. It needs to return entry.object somehow?