Manuel Schoebel
Thursday, 07. November 2013

Asynchronous function in a Meteorjs method call

Often times we want to call a server method from the client and return a value. It happens, that on the server we call an asynchronous function. That means we have to wait for the result and then return it to the client. There are different approaches how to do this, but we use the Meteor._wrapAsync function for that job.

In this example we want to create a session for a video chat with tokbox. On the client side a user clicks a button to create the video chatroom.{
  'click .create-session': function(evt, tpl) {
      Etc.prevent(evt); // helper that 'preventsDefault' and also 'stops propagation''createSession',, function(err) {
      if(err) { return Notify.setError(err.reason); }

On the server we defined the method createSession

  createSession: function(bookingId) {
    var createTokboxSessionASync, createTokboxSessionSync, key, location, openTok, secret, sessionId;

    key = Meteor.settings["public"].tokbox.apiKey; // it is public key, don't worry :-)
    secret = Meteor.settings.tokbox.secret;
    location = '';
    openTok = new OpenTok.OpenTokSDK(key, secret);

    // write a wrapper function for your asynchronous function
    createTokboxSessionASync = function(location, cb) {
        return openTok.createSession(location, function(sId) {
            // unfortunately tokbox does not implement the convention
            // of an error as the first parameter: shame on you! ;-)
              return cb(null, sId);

        // make the asynchronous function synchronous with _wrapAsync
        createTokboxSessionSync = Meteor._wrapAsync(createTokboxSessionASync);
        sessionId = createTokboxSessionSync(location);


I like this approach much more than working with Fibers directly because it is not that ugly, even though it is far from beautiful! But wrapAsynch (as the ’’ indicates) is not a final approach of dealing with asynchronous code in method calls, so i guess there will be something more handy in the hopefully near future.

Teile den Artikel, wenn er dir gefallen hat:

Du willst wissen wenn es etwas Neues gibt?
Dann melde dich kurz bei meinem Newsletter an!

Durch Anmeldung bei meinem Newsletter willigst du zur Erfolgsmessung, dem Einsatz des Versanddienstleisters MailChimp und Protokollierung der Anmeldung zu. Mehr Informationen dazu und zu deinen Widerrufsrechten findest du hier in der Datenschutzerklärung.