我的客户端正在调用服务器。
Meteor.call('someRequest', params, onAllDoneCallback);
由(服务器代码)处理
Meteor.methods({
'someRequest': function(params, cb) {
anAsyncFunction(params, cb);
return true;
},
});
我想要
onAllDoneCallback
一旦anAsyncFunction
在客户端触发已完成并触发自己的回调。然而,在 Meteor 中似乎是
someRequest
的第二个参数。被忽略并且 onAllDoneCallback
由什么触发 someRequest
返回,这里是 true
并在此之前调用 anAsyncFunction
已完成。在我的情况下,我更关心时间问题(我用它来告诉客户端处理已经完成,而不仅仅是请求被很好地接收),但其他人可能想用来自的参数调用回调
anAsyncFunction
最佳答案
您现在正在做的是将一个函数传递给服务器。如果那行得通,那是非常不安全的。您要做的是创建一个 future ,然后使用它来管理异步功能。下面是一个例子:
let Future = Npm.require('fibers/future');
Meteor.methods({
someRequest: function (someArg) {
// for security reasons, make sure you check the type of arguments.
check(someArg, String);
// future is an async handler.
let future = new Future();
// this is a function for a generic node style callback [ie, function (err, res)]
let resolver = future.resolver();
// run your function and pass it the future resolver
// the future will be resolved when the callback happens.
anAsyncFunction(someArg, resolver);
// this meteor method will not end until future has been resolved.
return future.wait();
}
});
或者,Meteor 提供了一个
wrapAsync
它提供了在 future 中包装异步函数的类似功能,以便它们可以在 meteor 方法中运行。那是:let wrappedAsyncFunction = Meteor.wrapAsync(anAsyncFunction /** second argument is `this` binding*/);
return wrappedAsyncFunction();
关于asynchronous - 如何在执行异步调用的 meteor 方法上执行回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35022295/