当前位置: 代码迷 >> JavaScript >> 流星服务器异步方法调用并使用返回结果
  详细解决方案

流星服务器异步方法调用并使用返回结果

热度:11   发布时间:2023-06-13 11:27:14.0

我有一个在服务器端执行大量计算的方法,我需要调用此方法两次,并使用这些调用的结果进行另一次计算:

combinationCalc: function(val1, val2) {
  var result1 = heavyCompute(val1);
  var result2 = heavyCompute(val2);

  return anotherComputation(result1, result2);
}

result2的值不依赖于result1的值,我如何异步执行这两个计算?

我想分享通过一些研究发现的自己的解决方案。 这需要使用NPM封装光纤/期货

Future = Meteor.npmRequire('fibers/future');

combinationCalc: function(val1, val2) {
  var fut1 = new Future();
  var fut2 = new Future();

  heavyCompute(val1, fut1);
  heavyCompute(val2, fut2);

  var result1 = fut1.wait();
  var result2 = fut2.wait();

  return anotherComputation(result1, result2);
}


heavyCompute(val, fut) {
  // ALL THE COMPUTES!
  fut.return(compute_result);
}

我希望在服务器上有一个单一的入口点,并尽可能减少混乱的代码。

您可以使用从客户端调用并异步运行的 。

首先在服务器上声明方法:

Meteor.methods({
  firstMethod: function (arg) {
    this.unblock();
    //do stuff
  },
  secondMethod: function (arg) {
    this.unblock();
    //do stuff
  }
});

注意this.unblock();的使用this.unblock(); 它允许从客户端运行方法调用而无需等待上一个调用( )。

然后,从客户端调用方法(您也可以从服务器调用它们):

Meteor.call('firstMethod', arg, function(error, result() {
  //do something with the result
});
Meteor.call('secondMethod', arg, function(error, result() {
  //do something with the result
});

使用流星方法和会话变量,您可以异步调用流星方法,将结果保存到会话变量中,并在两个参数都准备好后执行第二个方法调用。

combinationCalc: function(val1, val2) {

  // Calls heavyCompute on val1
  Meteor.call('heavyCompute', val1, function(error, result) {
    Session.set('result1', result);
    // if heavyCompute on val2 finished first
    if(Session.get('result1') && Session.get('result2'))
      Meteor.call('anotherComputation', Session.get('result1'), Session.get('result2'), function(error, result) {
         Session.set('answer', result);
      });
  });

  // Calls heavyCompute on val2
  Meteor.call('heavyCompute', val2, function(error, result) {
    Session.set('result2', result);
    // if heavyCompute on val1 finished first
    if(Session.get('result1') && Session.get('result2'))
      Meteor.call('anotherComputation', Session.get('result1'), Session.get('result2'), function(error, result) {
         Session.set('answer', result);
      });
  });
}

然后,只需调用Session.get('answer'); 您想在哪里使用结果。

为了最大程度地减少冗余代码,可以将检查未定义的内容放在anotherComputation方法本身内。

  相关解决方案