node.js 使 while 循环同步
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15902211/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Making the while loop synchronous
提问by ericbae
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
);
采纳答案by Andreas Hultgren
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.
您正在寻找async.while()。此解决方案假设您实际上想要一个接一个地执行每个请求。正如@UpTheCreek 提到的(编辑:我提到的评论已被编辑)可能可以异步执行并使用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!
});
回答by katspaugh
With whileyou get a busy loop, which is counter-purpose in Node.
随着while你得到一个繁忙的循环,这是反目的节点。
Make it a recursive function instead. Each call will be done in a separate tick.
使它成为一个递归函数。每次调用都将在单独的勾号中完成。
var page = 2;
var last_page = 100;
(function loop() {
if (page <= last_page) {
request("/data?page=" + page, function (error, response, body) {
if (!error && response.statusCode == 200) {
store_data(body)
}
page++;
loop();
});
}
}());
回答by seanbehan
You can also wrap your while loop in async and break after your promise resolves/conditions have been met...
您还可以将您的 while 循环包装在异步中,并在您的承诺解决/条件得到满足后中断...
const request = require("request")
;(async()=>{
let results = []
while(true){
await new Promise(resolve => {
request('http://www.seanbehan.com/', (err, resp, body)=>{
console.log(new Date, 'Downloading..')
results.push(body)
resolve(body)
})
})
if(results.length >= 5){
break
}
}
console.log(results)
})()

