如何在执行异步调用的流星方法上执行回调?

Gui*_*uig 5 methods asynchronous callback meteor

我的客户端正在调用服务器。

Meteor.call('someRequest', params, onAllDoneCallback);
Run Code Online (Sandbox Code Playgroud)

由(服务器代码)处理

Meteor.methods({
    'someRequest': function(params, cb) {
        anAsyncFunction(params, cb);
        return true;
    },
});
Run Code Online (Sandbox Code Playgroud)

onAllDoneCallback一旦anAsyncFunction完成并触发自己的回调,我希望在客户端触发。

然而,在 Meteor 中,似乎someRequest忽略了第二个参数,并且onAllDoneCallback触发了someRequest返回的内容,这里是true哪个,哪个在anAsyncFunction完成之前被调用。

在我的情况下,我更关心时间问题(我用它来告诉客户端处理已经完成,而不仅仅是请求被很好地接收),但其他人可能想用来自的参数调用回调 anAsyncFunction

cor*_*vid 4

您现在要做的是将函数传递给服务器。如果这确实有效,那就非常不安全。您想要做的是创建一个 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();
  }
});
Run Code Online (Sandbox Code Playgroud)

或者,Meteor 提供了wrapAsync类似的功能,将异步函数包装在 future 中,以便它们可以在 Meteor 方法中运行。那是:

let wrappedAsyncFunction = Meteor.wrapAsync(anAsyncFunction /** second argument is `this` binding*/);
return wrappedAsyncFunction();
Run Code Online (Sandbox Code Playgroud)