gpt4 book ai didi

node.js - 如何在each()函数内运行异步代码?

转载 作者:太空宇宙 更新时间:2023-11-03 22:54:44 25 4
gpt4 key购买 nike

我需要能够在每个循环内运行异步代码,并且在异步代码完成之前不进行迭代。

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

最佳答案

尝试使用async's whilst 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
}
);

关于node.js - 如何在each()函数内运行异步代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24231554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com