gpt4 book ai didi

javascript - 两个for循环内的node.js同步请求

转载 作者:行者123 更新时间:2023-12-03 10:17:01 25 4
gpt4 key购买 nike

我想让我的代码同步,因为如果我们以异步方式发送太多请求,Google 就会阻止。

for (var i = 0; i < titles.length; i++) {
for (var j = 0; j < filter.length; j++) {
(function(e,u){
console.log(titles[e]+" - "+filter[u]);
request('http://suggestqueries.google.com/complete/search? client=chrome&output=json&hl=tr&q='+ titles[e] +" "+filter[u] ,{"json":true,"encoding":"binary"}, function (error, response, tags) {
console.log(tags.toString());
});

}(i,j));

}
}

这段代码工作正常,但它是异步的,我知道如何用一个循环来完成它,但我不知道如何使用两个循环。

最佳答案

您可以尝试使用async.jseachSeries ,像这样

var requests = [];

for (var i = 0; i < titles.length; i++) {
for (var j = 0; j < filter.length; j++) {
requests.push({title: titles[i], filter: filter[j]});
}
}

async.eachSeries(requests, function (req, next) {
request('http://suggestqueries.google.com/complete/search?client=chrome&output=json&hl=tr&q=' + req.title + " " + req.filter, {
json: true,
encoding: 'binary'
}, function(error, response, tags) {
console.log(tags.toString());

next(error);
});
}, function () {
console.log('done');
});

The next iterator is only called once the current one has completed. This means the iterator functions will complete in order.

关于javascript - 两个for循环内的node.js同步请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29828004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com