Search code examples
node.jsasync-awaitkurento

Writing async/await version of a callback


I'm trying to rewrite a callback as async/await but following code doesn't work and results in high CPU at the commented line.

const kurento = require('kurento-client')

function getKurentoClient (kmsUrl) {
  return new Promise((resolve, reject) => {
    kurento(kmsUrl, (error, kurentoClient) => {
      if (error) {
        return reject(error)
      } else {
        return resolve(kurentoClient) // never returns
      }
    })
  })
}

async function test () {
  let result = await getKurentoClient('ws://localhost:8888/kurento')
  console.log('done')
}

test()

Solution

  • From the mozilla.org website:

    The Promise.resolve(value) method returns a Promise object that is resolved with the given value. If the value is a thenable (i.e. has a "then" method), the returned promise will "follow" that thenable, adopting its eventual state; if the value was a promise, that object becomes the result of the call to Promise.resolve; otherwise the returned promise will be fulfilled with the value.

    And from bluebird GitHub:

    when promises resolve other promises or things with then(aka thenables, like _kurentoClient in this case) - they have to wait for it to call then itself.

    As you have guessed, kurento clients have a then function (so is a thenable) so the Promise is trying to resolve it. Because of a bug (or not a bug. Honestly, I have not researched enough to determine that) it keeps resolving itself forever.

    As far as I see, seems that this kurento commit tries to fix it, resolving to an "untheanble". I see that the commit is from 31 Oct 2016 but the latest release is from Sep 2016 so I think that the fixed version is not deployed.