Writing/Converting Meteor Synchronous Functions

依然范特西╮ 提交于 2019-12-10 14:42:45

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/19616776/writing-converting-meteor-synchronous-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!