Meteor Async
Set of async utilities to work with NPM modules and other async code blocks.
Installation
meteor add meteorhacks:async
API
Available in the Server Side only
Meteor APIs are executed synchronously. Most of the NodeJS modules works asynchronously. So we need a way to bride the gap. Async Utilities comes to rescue you.
Async.runSync(function)
Async.runSync()
pause the execution until you invoke done()
callback as shown below.
1var response = Async.runSync(function(done) { 2 setTimeout(function() { 3 done(null, 1001); 4 }, 100); 5}); 6 7console.log(response.result); // 1001
done()
callback takes 2 arguments. error
and the result
object. You can get them as the return value of the Async.runSync()
as shown as response in the above example.
return value is an object and it has 2 fields. error
and result
.
Meteor.sync(function)
Same as Async.runSync
but deprecated.
Async.wrap(function)
Wrap an asynchronous function and allow it to be run inside Meteor without callbacks.
1 2//declare a simple async function 3function delayedMessge(delay, message, callback) { 4 setTimeout(function() { 5 callback(null, message); 6 }, delay); 7} 8 9//wrapping 10var wrappedDelayedMessage = Async.wrap(delayedMessge); 11 12//usage 13Meteor.methods({ 14 'delayedEcho': function(message) { 15 var response = wrappedDelayedMessage(500, message); 16 return response; 17 } 18});
If the callback has a result, it will be returned from the wrapped function. If there is an error, it will be thrown.
Async.wrap(function)
is very similar toMeteor._wrapAsync
.
Async.wrap(object, functionName)
Very similar to Async.wrap(function)
,
but this API can be used to wrap an instance method of an object.
1var github = new GithubApi({ 2 version: "3.0.0" 3}); 4 5//wrapping github.user.getFrom 6var wrappedGetFrom = Async.wrap(github.user, 'getFrom');
Async.wrap(object, functionNameList)
Very similar to Async.wrap(object, functionName)
,
but this API can be used to wrap multiple instance methods of an object.
1GithubApi = Npm.require('github'); 2 3var github = new GithubApi({ 4 version: "3.0.0" 5}); 6 7//wrapping github.user.getFrom and github.user.getEmails 8var wrappedGithubUser = Async.wrap(github.user, ['getFrom', 'getEmails']); 9 10//usage 11var profile = wrappedGithubUser.getFrom({user: 'arunoda'}); 12var emails = wrappedGithubUser.getEmails();