如何在每个()函数内运行asynchronous代码?

我需要能够在每个循环内运行asynchronous代码,而不是直到asynchronous代码完成。

$("#items").children(".block-option-small").each(function(item){ request(newurl,function(err, resp, body) { $ = cheerio.load(body);}); }); 

尝试使用asynchronous的同时function :

 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); 

希望这可以帮助。