使while循环同步 [英] Making the while loop synchronous
本文介绍了使while循环同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一段代码
var page = 2;
var last_page = 100;
while(page <= last_page) {
request("http://some_json_server.com/data?page=" + page, function (error, response, body) {
if (!error && response.statusCode == 200) {
store_data(body)
}
page++;
});
}
我已经完成了以下操作,但实际上并没有检索任何内容。我这样做是否正确?
I've done the following, but it is actually not retrieving anything. Am I doing this correctly?
var page = 2;
var last_page = 100;
while(page <= last_page) {
var async_arr = [];
async_arr.push(
function(next) {
request("http://some_api_url?page=" + page, function (error, response, body) {
if (!error && response.statusCode == 200) {
store_data(body);
}
});
}
);
async.series(
async_arr, done
);
推荐答案
您正在寻找 async.whilst()。这个解决方案假设您实际上想要在另一个之后执行每个请求。正如@UpTheCreek提到的那样(编辑:我提到的评论被编辑过),很可能会异步进行,并使用 async.parallel $跟踪每个结果c $ c>。
You're looking for async.whilst(). This solution is assuming you actually want to do each request after the other. As @UpTheCreek mentions (edit: the comment I referred to was edited) it would likely be possible to do it asynchronously and keep track of each result using async.parallel
.
var page = 2,
lastPage = 100;
async.whilst(function () {
return page <= lastPage;
},
function (next) {
request("http://some_json_server.com/data?page=" + page, function (error, response, body) {
if (!error && response.statusCode == 200) {
store_data(body)
}
page++;
next();
});
},
function (err) {
// All things are done!
});
这篇关于使while循环同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文