如何在Meteor中批量运行异步调用?

时间:2015-01-10 18:32:35

标签: javascript multithreading asynchronous meteor

我正在尝试在Meteor中异步进行多个API调用。我想同时运行一些函数,然后当它们完成时,能够使用所有这些结果来做其他事情。下面概述了我的意思:

Http.get(something)
Http.get(something else)
Http.get(something more)
Http.get(something even else more)

我希望能够同时运行这些,然后在完成后立即访问所有数据。在Meteor中做这样的事情的最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

我假设你想要在Meteor.methods

中做一些事情

对于您的案例使用,您可以在流星中使用http包。

http包的使用是双重的 - 它可以充当同步或异步,具体取决于您使用它的方式。

首先使用meteor add http

为您的项目添加包

然后。 如果您使用

result = Meteor.http.get("http://headers.jsontest.com/")
console.log('output of http.get here ' + result)

并且没有将第二个参数传递给http.get作为" async回调函数",它表现为同步调用,即get的输出将在result变量

你正在传递第二个参数

  result = Meteor.http.get("http://ip.jsontest.com/", function(err, res){
    console.log('output of http.get here ' + JSON.stringify(res))
  })

它的行为与异步调用一样,http.get的结果将在res内部回调,而不是result变量

在您的情况下,请先使用

  result2 = Meteor.http.get("http://headers.jsontest.com/")
  result3 = Meteor.http.get("http://date.jsontest.com/")
  console.log("result 2 here " + result2)
  console.log("result 3 here "+ result3)

现在,result2result3你可以做任何你想要的事情

为了您的参考我在meteorpad中创建了示例 - 请查看它 - http://meteorpad.com/pad/E8w3xRFor9rfX7YMX/sample-stackoverflow-example

查看someMethod文件中的common.js

您可以使用 - Meteor.call('someMethod')从客户端调用此方法并检查服务器控制台上的输出

您需要从此处访问以上应用 - http://app-tedmqdye.meteorpad.com/ 你可以从右窗格中获取它

答案 1 :(得分:0)

至于让那些并行运行并检测到最后一次返回的时间,我不知道。如果您不介意按顺序运行它们,那些Http.gets遵循节点回调样式,因此您应该能够使用wrapAsync()函数将其转换为伪同步,这意味着您将获得回调的结果作为每次通话的返回值(虽然他们将使用期货,因此他们不会阻止)。您可以查看Meteor.wrapAsync或Arunoda的async包,了解将异步方法转换为同步的方法(我过于简单,但效果相同)。以下是您可以做的一个示例:

syncGet = Meteor.wrapAsync(Http.get)

res1 = syncGet(url1, options1)
res2 = syncGet(url2, options2)
res3 = syncGet(url3, options3)
res4 = syncGet(url4, options4)

// Do something with the above results here

如果你还不熟悉的话,这里有关于Meteor同步和异步功能的精彩读物: https://www.discovermeteor.com/blog/understanding-sync-async-javascript-node/

除此之外,您还可以在前一个回调中嵌套每个调用,这看起来非常粗略,并且仍然具有串行运行的效果。

注意:如果您严格从服务器运行此命令,请参阅Adjuke的答案,在这种情况下会更简单一些。

相关问题