Meteor:在Meteor.method中调用asynchronous函数并返回结果

我想在一个Meteor方法中调用一个asynchronous函数,然后将该函数的结果返回给Meteor.call。

(如何)是可能的?

Meteor.methods({ my_function: function(arg1, arg2) { //Call other asynchronous function and return result or throw error } }); 

毛泽东是对的。 Meteor现在有了Meteor.wrapAsync()这种情况。

以下是通过stripe执行计费的最简单的方法,并且还传递一个callback函数:

 var stripe = StripeAPI("key"); Meteor.methods({ yourMethod: function(callArg) { var charge = Meteor.wrapAsync(stripe.charges.create, stripe.charges); charge({ amount: amount, currency: "usd", //I passed the stripe token in callArg card: callArg.stripeToken, }, function(err, charge) { if (err && err.type === 'StripeCardError') { // The card has been declined throw new Meteor.Error("stripe-charge-error", err.message); } //Insert your 'on success' code here }); } }); 

我发现这个post真的有用: meteor:在服务器上正确使用Meteor.wrapAsync

使用未来做到这一点。 喜欢这个:

 Meteor.methods({ my_function: function(arg1, arg2) { // Set up a future var fut = new Future(); // This should work for any async method setTimeout(function() { // Return the results fut.ret(message + " (delayed for 3 seconds)"); }, 3 * 1000); // Wait for async to finish before returning // the result return fut.wait(); } }); 

更新

要从Meteor 0.5.1开始使用Future,必须在Meteor.startup方法中运行以下代码:

 Meteor.startup(function () { var require = __meteor_bootstrap__.require Future = require('fibers/future'); // use Future here }); 

更新2

要从Meteor 0.6开始使用Future,必须在Meteor.startup方法中运行以下代码:

 Meteor.startup(function () { Future = Npm.require('fibers/future'); // use Future here }); 

然后使用return方法而不是ret方法:

 Meteor.methods({ my_function: function(arg1, arg2) { // Set up a future var fut = new Future(); // This should work for any async method setTimeout(function() { // Return the results fut['return'](message + " (delayed for 3 seconds)"); }, 3 * 1000); // Wait for async to finish before returning // the result return fut.wait(); } }); 

看到这个要点 。

Meteor的最新版本提供了未Meteor._wrapAsync函数,它将一个带有标准(err, res)callback函数的函数转换为一个同步函数,这意味着当前的Fibre产生,直到callback返回,然后使用Meteor.bindEnvironment来确保您保留当前的Meteor环境variables(例如Meteor.userId())

一个简单的用法如下:

 asyncFunc = function(arg1, arg2, callback) { // callback has the form function (err, res) {} }; Meteor.methods({ "callFunc": function() { syncFunc = Meteor._wrapAsync(asyncFunc); res = syncFunc("foo", "bar"); // Errors will be thrown } }); 

您可能还需要使用function#bind asyncFunc来确保在包装asyncFunc之前使用正确的上下文来调用它。

欲了解更多信息,请参阅: https : //www.eventedmind.com/tracks/feed-archive/meteor-meteor-wrapasync

另一个select是这个包达到类似的目标。

 meteor add meteorhacks:async 

从包装自述文件:

Async.wrap(function)

包装一个asynchronous函数,并允许它在没有callback的情况下在Meteor中运行。

 //declare a simple async function function delayedMessge(delay, message, callback) { setTimeout(function() { callback(null, message); }, delay); } //wrapping var wrappedDelayedMessage = Async.wrap(delayedMessge); //usage Meteor.methods({ 'delayedEcho': function(message) { var response = wrappedDelayedMessage(500, message); return response; } });