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.
Template.videoChat.events({
'click .create-session': function(evt, tpl) {
Etc.prevent(evt); // helper that 'preventsDefault' and also 'stops propagation'
Meteor.call('createSession', tpl.data.booking._id, function(err) {
if(err) { return Notify.setError(err.reason); }
});
}
});
On the server we defined the method createSession
Meteor.methods({
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 = '127.0.0.1';
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.
Du willst wissen wenn es etwas Neues gibt?
Dann melde dich kurz bei meinem Newsletter an!