的NodeJS - 使while循环同步 [英] NodeJS - making the while loop synchronous
本文介绍了的NodeJS - 使while循环同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有如下一段code的
VAR页= 2;
VAR last_page = 100;
而(页面< = last_page){
请求(http://some_json_server.com/data?page=+页,功能(错误,响应体){
如果(误差放大器和;!&安培; response.status code == 200){
store_data(体)
}
++页面;
});
}
我已经做以下,但实际上没有任何东西取回。我在做正确吗?
VAR页= 2;
VAR last_page = 100;
而(页面< = last_page){
变种async_arr = [];
async_arr.push(
功能(下){
请求(HTTP:// some_api_url页=+页,功能(错误,响应体){
如果(误差放大器和;!&安培; response.status code == 200){
store_data(体);
}
});
}
);async.series(
async_arr,做
);
解决方案
您正在寻找 async.whilst()。该解决方案是假设你真正想做的事情后,其他每个请求。由于@UpTheCreek提到(的修改的:我所指被编辑评论)它可能会是可能的异步做,跟踪使用每个结果的 async.parallel
。
VAR页= 2,
末页= 100;async.whilst(函数(){
返回页面< =末页;
},
功能(下){
请求(http://some_json_server.com/data?page=+页,功能(错误,响应体){
如果(误差放大器和;!&安培; response.status code == 200){
store_data(体)
}
++页面;
下一个();
});
},
功能(错误){
//所有的事情都做了!
});
I've got a following piece of code
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
);
解决方案
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!
});
这篇关于的NodeJS - 使while循环同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文