我需要能够在每个循环内运行异步代码,并且在异步代码完成之前不进行迭代。
$("#items").children(".block-option-small").each(function(item) {
request(newurl,function(err, resp, body) { $ = cheerio.load(body);});
});
尝试使用异步的 while 函数:
var async = require("async"),
request = require("request");
var items, count;
items = $("#items").children(".block-option-small");
count = 0;
async.whilst(
function() {
return count < items.length;
},
function(whilstCallback) {
var item;
item = items[count];
count++;
// build request url...
request(newurl, function(err, resp, body) {
$ = cheerio.load(body);
// more processing...
// process the next item
whilstCallback();
});
},
function(err) {
// called when all items have been processed
}
);
您不必为此使用该模块。你也可以这样写;
var items = $("#items").children(".block-option-small");
var count = items.length;
(function iterate(i) {
if (i === count) {
// iterations complete
// do what you want to once iterations are complete
process.exit(1);
}
var item = items[i];
// async code
request(newurl, function (err, resp, body) {
$ = cheerio.load(body);
iterate(i+1);
});
})(0);
希望这可以帮助。