javascript - Meteor:在 Meteor.method 中调用异步函数并返回结果

标签 javascript meteor

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

(怎么)这可能?

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

最佳答案

使用 Future 来做到这一点。像这样:

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();
  }
});

参见 this gist .

关于javascript - Meteor:在 Meteor.method 中调用异步函数并返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12569712/

相关文章:

javascript - 为什么 OR 在这个正则表达式中不起作用?

javascript - 2 与数据库相关的下拉菜单

meteor - React SSR - 处理 window.height/width

javascript - 将对象作为身份证件插入 mongodb

javascript - 更新数组内的对象 MongoDB Meteor

javascript - Meteor.js - 直接从 MongoDB 提供图像?

javascript - 如何使用 Firebug 或任何其他扩展找到哪些 Javascript 代码触发表单提交?

javascript - 正确卸载 react 组件

javascript - 包含 Alchemy js 的源代码会破坏 Highcharts js

express - Meteor:Paypal Express Checkout 集成