Meteor async methods

I just solved a "bug" that I had been experiencing with our Meet on V product. We needed to create session credentials for watch parties. The trouble was that the Meteor method was returning before the credentials had returned.

The solution was to use Promises in Meteor which are a bit special. Meteor uses Fibers and you have to wrap any Meteor code in those. Let's look at the code.

const bound = Meteor.bindEnvironment((callback) => callback())

Meteor.methods({
  // MEETING ROOMS
  'vonage.makeSession': async function (meetId) {
    const OpenTok = require('opentok')
    const opentok = new OpenTok('#############', '################', { timeout: 50000 })

    // console.log('1: VONAGE MAKE SESSION CALLED server')
    return new Promise(function (resolve, reject) {
      opentok.createSession({ mediaMode: 'routed', archiveMode: 'manual' }, function (err, session) {
        if (err) console.error(err)
        bound(() => {
          VonageIds.upsert({ meetId }, { $set: { session: session } })
        })
        resolve(session)
      })
    })
  },
})

Let's start in the middle and work out. We're using the OpenTok platform which is great for providing in-app video experiences. You have to create session credentials first. This all takes more than 0 ms, so we have to wrap that in a promise.

Within that, there's also the bound() defined at the beginning.

Resources: