编写/转换流星同步功能 [英] Writing/Converting Meteor Synchronous Functions

查看:124
本文介绍了编写/转换流星同步功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这已经困扰了我一段时间,所以我想我只是做一个快速的QA就可以了:

如果之一具有正常的NodeJS模块或东西,其对服务器侧的异步函数。我如何使它同步。例如我怎么会转换的NodeJS fs.stat 异步函数和一个同步。<​​/ P>

例如我有

服务器端的js

  Meteor.methods({
    getStat:功能(){
        fs.stat('的/ tmp /你好',函数(ERR,结果){
            如果(ERR)抛出走错了路。
            的console.log(结果)
        });
    }
});

如果我把它从客户端,我回去未定义我的结果,因为结果是一个回调。


解决方案

有一个名为函数(无证) Meteor.wrapAsync

简单地包裹起来的功能。

  Meteor.methods({
    getStat:功能(){
        VAR getStat = Meteor._wrapAsync(fs.stat);        返回getStat('的/ tmp /你好');
    }
});

现在你会得到这个在你的 Meteor.call 结果的结果。可以转换有所回调,其中第一个参数是一个错误,第二个结果的异步功能。

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.

解决方案

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.

这篇关于编写/转换流星同步功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆