Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing/Converting Meteor Synchronous Functions

This has been bothering me for a while so I thought I'd just do a quick QA on it:

If one has a normal nodeJS module or something and it has a async function on the server side. How do I make it synchronous. E.g how would I convert the nodejs fs.stat asynchronous function to a synchronous one.

e.g I have

server side js

Meteor.methods({
    getStat:function() {
        fs.stat('/tmp/hello', function (err, result) {
            if (err) throw err;
            console.log(result)
        });
    }
});

If I call it from the client I get back undefined as my result because the result is in a callback.

like image 379
Tarang Avatar asked Oct 27 '13 09:10

Tarang


1 Answers

There is a function (undocumented) called Meteor.wrapAsync.

Simply wrap the function up

Meteor.methods({
    getStat:function() {
        var getStat = Meteor._wrapAsync(fs.stat);

        return getStat('/tmp/hello');
    }
});

Now you will get the result of this in the result of your Meteor.call. You can convert any async function that has a callback where the first parameter is an error and the second the result.

like image 179
2 revs Avatar answered Nov 15 '22 12:11

2 revs