简体   繁体   English

meteor - 在返回之前同步多个异步查询?

[英]meteor - Synchronizing multiple async queries before returning?

So I have a Meteor method that is supposed to tell the server to send multiple API requests to 3rd party APIs, and then combine the results of these queries into one array, which is returned to the client. 所以我有一个Meteor方法,它应该告诉服务器向第三方API发送多个API请求,然后将这些查询的结果合并到一个数组中,然后返回给客户端。

However, I can't seem to find a way for the server to wait until all the API queries have completed before returning the result. 但是,在返回结果之前,我似乎找不到服务器等待所有API查询完成的方法。

The synchronous version of the code, which just fetches the data API call after another, goes like this: 代码的同步版本只是一个接一个地获取数据API调用,如下所示:

Meteor.methods({
    fetchData: function(APILinks) {
        var data = [];
        APILinks.forEach(function(APILink) {
            var items = HTTP.get(APILink).content.items;
            items.forEach(function (item) {
                data.push(item);
            });
        });
        return items;
    }
});

This synchronous code works. 这个同步代码有效。 However, I haven't been able to find a good way to make the API requests async. 但是,我无法找到使API请求异步的好方法。 The closest I could get to a solution was to redefine the method to return the result of only one API request, and then have the client side loop through each of the API link and calling the method for each one of them. 我能找到最接近解决方案的方法是重新定义方法以返回仅一个API请求的结果,然后让客户端循环遍历每个API链接并为每个API链接调用方法。 However, is there a way to wrap all these requests into one nice method that returns only when all the API requests are complete ? 但是,有没有办法将所有这些请求包装成一个很好的方法, 只有在所有API请求完成后才返回?

You have to use the asynchronous version of HTTP.get and collect the results using Future s. 您必须使用HTTP.get的异步版本并使用Future s收集结果。

I made up a simple example using setTimeout s to simulate HTTP requests so that you understand the principle, I advise you start from this code and replace the dummy setTimeout with your HTTP get request. 我编写了一个使用setTimeout来模拟HTTP请求的简单示例,以便您了解原理,我建议您从此代码开始并使用HTTP get请求替换虚拟setTimeout

The example is a test server method which takes a number of tasks (n) as a parameter, it then launches n tasks that each compute the square of their index in index seconds. 该示例是一个test服务器方法,它将许多任务(n)作为参数,然后启动n个任务,每个任务以索引秒计算其索引的平方。

// we use fibers which is a dependency of Meteor anyway
var Future = Npm.require("fibers/future");

Meteor.methods({
    test: function(n) {
        // build a range of tasks from 0 to n-1
        var range = _.range(n);
        // iterate sequentially over the range to launch tasks
        var futures = _.map(range, function(index) {
            var future = new Future();
            console.log("launching task", index);
            // simulate an asynchronous HTTP request using a setTimeout
            Meteor.setTimeout(function() {
                // sometime in the future, return the square of the task index
                future.return(index * index);
            }, index * 1000);
            // accumulate asynchronously parallel tasks
            return future;
        });
        // iterate sequentially over the tasks to resolve them
        var results = _.map(futures, function(future, index) {
            // waiting until the future has return
            var result = future.wait();
            console.log("result from task", index, "is", result);
            // accumulate results
            return result;
        });
        //
        console.log(results);
        return results;
    }
});

Type > Meteor.call("test",3,function(error,result){console.log(result);}); 键入> Meteor.call("test",3,function(error,result){console.log(result);}); in your browser console. 在浏览器控制台中。 This will output [0,1,4] after 3 seconds. 这将在3秒后输出[0,1,4]

In your server console, this will output : 在您的服务器控制台中,这将输出:

// immediately :
launching task 0
launching task 1
launching task 2
// after 1 second :
result from task 0 is 0
// after 2 seconds :
result from task 1 is 1
// after 3 seconds :
result from task 2 is 4
[ 0, 1, 4 ]

The HTTP.get asynchronous version is detailed in Meteor docs : HTTP.get异步版本在Meteor docs中有详细说明:

http://docs.meteor.com/#http_call http://docs.meteor.com/#http_call

If you want to understand better the whole Future concept, refer to the fibers docs : 如果您想更好地了解整个Future概念,请参阅光纤文档:

https://github.com/laverdet/node-fibers https://github.com/laverdet/node-fibers

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM