asynchronous - 如何在执行异步调用的 meteor 方法上执行回调?

标签 asynchronous meteor methods callback

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

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/

相关文章:

php - 在 WooCommerce 中更改现有订单的订单项名称

带有两个参数的 iPhone 方法声明

java - 多次启动一个方法

javascript - 在 Parse.com 的 Cloud 代码中,异步代码为 for 循环中的变量提供了错误的值

node.js - 如何在不同时区的同一时间运行 cron?

Javascript - 如果是异步情况

javascript - Meteor:分享模板

javascript - onchange 上的 keyup 验证不适用于meteor js

javascript - 一旦父 http 请求中的所有子 http 请求完成,我如何返回

python - 为什么 Nodejs 可以做文件 I/O 异步而 Python asyncio 不能?