Meteor:如何使用Meteor.call从服务器返回数据

问题描述:

当我在客户端上执行以下操作时:

When I do the following on the client:

Meteor.call('fileUpload', fileInfo, fileData, function(err, response) {
    ....
});

在回调中,我需要回复。所以在服务器上我有

In the callback I need the response. So on the server I have

Meteor.methods = {
   fileUpload: function (fileInfo, fileData) {

   fs.writeFile(path, fileData, "binary", function (err) {
       if (err) 
           return 'error';
       ...
       return { ..... };
  }
  //return 'this works';

}

不幸的是我在客户端没有收到任何东西。问题是服务器运行异步代码( fs .writeFile )。如果我取消注释最后一行我收到的东西。所以问题是:当我运行异步代码时,我可以将某些东西返回给客户端吗?

Unfortunately I don't receive anything on the client. The problem is that the server runs async code (fs.writeFile). If I uncomment the last line I receive something back. So the question is: can I return something back to the client when I run async code ?

Meteor使用光纤来允许异步代码以顺序方式写入,以防止在回调地狱中结束。它们为光纤提供了未来的抽象层。

Meteor uses fibers to allow async code to be written in a sequential way to prevent ending up in callback hell. They provide future as abstraction layer to fibers.

var Future = Npm.require('fibers/future');
var result  = Future.wrap(fs.writeFile)(path, fileData, "binary").wait();

这将异步writeFile方法包装在光纤中。

This wraps the async writeFile method in a fiber.

阅读以下文章,以更好地解释纤维的工作原理:

http://meteorhacks.com/fibers-eventloop-and-meteor.html

Read the following article for better explaination of how fibers work:
http://meteorhacks.com/fibers-eventloop-and-meteor.html

流星团队不建议使用原纤维api 。 Src: https://www.npmjs.org/package/fibers 关于期货的部分

The meteor team doesn't recommend using the raw fibers api. Src: https://www.npmjs.org/package/fibers section about futures

Async.wrap Future.wrap 基本上做同样的事情。
但是有一个很大的区别Async.wrap会隐藏未来并且不会让你使用.wait()因为包装函数实际上不会返回未来但会返回未来返回的内容。

Async.wrap and Future.wrap basically do the same thing. But there is one big difference Async.wrap hides the future and doesn't make you use .wait() because the wrapped function doesn't actually return the future but returns whatever the future returns.

最后你可以使用我个人喜欢future.wrap,因为我想知道我正在使用光纤和放大器。期货,我不喜欢那种对我隐瞒。

In the end you can use both I would personally favor future.wrap because I like to be aware of that I am working with fibers & futures and I do not like that being hidden from me.

var wrappedSomeMethod = Async.wrap(someMethod);
wrappedSomeMethod();

比以下更简洁:

var wrappedSomeMethod = Future.wrap(someMethod);
wrappedSomeMethod().wait();

未来的高级使用

它还允许你在不同的期货例子中运行多个东西:

And it also lets you run multiple things in different futures example:

var fooFuture = bar();
var wuFuture = bar();

var fooResult = fooFuture.wait();
var wuResult = wuFuture.wait();

应该更快,因为您没有暂停当前光纤以启动下一个

Should be faster because you are not pausing the current fiber to start the next