流星 - 在返回之前同步多个异步查询? [英] meteor - Synchronizing multiple async queries before returning?

查看:21
本文介绍了流星 - 在返回之前同步多个异步查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个 Meteor 方法,它应该告诉服务器向 3rd 方 API 发送多个 API 请求,然后将这些查询的结果组合成一个数组,返回给客户端.

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.

但是,我似乎无法找到让服务器等待所有 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:

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

此同步代码有效.但是,我一直无法找到使 API 请求异步的好方法.我能得到的最接近解决方案是重新定义方法以仅返回一个 API 请求的结果,然后让客户端循环遍历每个 API 链接并为每个 API 链接调用该方法.但是,有没有办法将所有这些请求包装成一个很好的方法,该方法仅在所有 API 请求完成时返回?

This synchronous code works. However, I haven't been able to find a good way to make the API requests async. 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. However, is there a way to wrap all these requests into one nice method that returns only when all the API requests are complete?

推荐答案

您必须使用 HTTP.get 的异步版本,并使用 Future 收集结果.

You have to use the asynchronous version of HTTP.get and collect the results using Futures.

我用setTimeouts做了一个简单的例子来模拟HTTP请求,让你理解原理,我建议你从这段代码开始,将虚拟的setTimeout替换为您的 HTTP 获取请求.

I made up a simple example using setTimeouts 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.

该示例是一个 test 服务器方法,它以多个任务 (n) 作为参数,然后启动 n 个任务,每个任务在索引秒内计算其索引的平方.

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.

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

输入<代码>>Meteor.call("test",3,function(error,result){console.log(result);}); 在浏览器控制台中.这将在 3 秒后输出 [0,1,4].

Type > Meteor.call("test",3,function(error,result){console.log(result);}); in your browser console. This will output [0,1,4] after 3 seconds.

在您的服务器控制台中,这将输出:

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 ]

HTTP.get 异步版本在 Meteor 文档中有详细说明:

The HTTP.get asynchronous version is detailed in Meteor docs :

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

如果您想更好地理解整个 Future 概念,请参阅纤维文档:

If you want to understand better the whole Future concept, refer to the fibers docs :

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

这篇关于流星 - 在返回之前同步多个异步查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆