如何按顺序从API处理异步的结果吗? [英] How to sequentially handle asynchronous results from API?
问题描述
这个问题可能有点模糊,但我会尽我所能解释的。
This question might be a little vague, but I'll try my best to explain.
我试图创造一切,我可以从Twitter的API获取鸣叫的数组,但是它限制了每个请求返回200鸣叫。我如何申请到Twitter异步高达3200的最大限制返回的鸣叫?这是什么意思是,是否可以异步调用Twitter的API,但构建阵列顺序,确保鸣叫排序正确有关日期?
I'm trying to create an array of all of the tweets that I can retrieve from Twitter's API, but it limits each request to 200 returned tweets. How can I request to Twitter asynchronously up to the maximum limit of 3200 returned tweets? What do I mean is, is it possible to asynchronously call Twitter's API but build the array sequentially, making sure that the tweets are correctly sorted with regard to date?
所以,我有一个数组:
var results = [];
和我使用节点的请求模块:
and I'm using node's request module:
var request = require('request');
我现在所拥有的(为200只的限制)是
what I have right now (for just the limit of 200) is
request(options, function(err, response, body) {
body = JSON.parse(body);
for (var i = 0; i < body.length; i++) {
results.push(body[i].text);
}
return res.json(results);
});
我已经研究过,也许用承诺的模块,但它是混乱的理解。我试图用一个while循环,但它得到复杂的,因为我无法按照服务器正在采取的路径。
I've looked into maybe using the 'promise' module, but it was confusing to understand. I tried using a while loop, but it got complicated because I couldn't follow the path that the server was taking.
让我知道,如果这没有解释的事情办好。
Let me know if this didn't explain things well.
在最后,我想结果是填充了所有请求发送的tweet的数组。
In the end, I want results to be an array populated with all of the tweets that the requests send.
推荐答案
我会建议使用请求 - 诺
而不是要求
。这里是我的解决方案。
I would suggest using request-promise
instead of request
. Here is my solution.
var rp = require('request-promise');
var tweets = [];
var promises = [];
for (var i =1; i< 10; i++){
var promise = rp(options);
promises.push(promise);
}
Promise.all(promises).then(function(data){
data.forEach(function(item){
// handle tweets here
});
return res.json(tweets);
});
这篇关于如何按顺序从API处理异步的结果吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!