gpt4 book ai didi

javascript - nodejs异步嵌套调用

转载 作者:搜寻专家 更新时间:2023-10-31 23:02:16 26 4
gpt4 key购买 nike

我想废弃一个 url:

1个获取元素列表的请求

每个结果有 1 个请求以获取详细信息

这是我的:

var request = require('request')
, cheerio = require('cheerio')
, async = require('async')
, format = require('util').format;

var baseurl = 'http://magiccards.info';
async.waterfall([
function (callback) {
request(baseurl + '/sitemap.html', function (err, response, body) {
var sets = [];
var $ = cheerio.load(body);
$('a[href$="/en.html"]').each(function () {
sets.push({"name": $(this).text(), "code":$(this).attr('href').match(/\/([^)]+)\//)[1], "path": $(this).attr('href'), "translations":[]});
});
callback(null, sets);
});
},
function (sets, callback) {
console.log(sets);
async.eachSeries(sets, function (set, callback) {
console.log('SET ' + set.code.toUpperCase());
request(baseurl + set.path, function (err, response, body) {
var $ = cheerio.load(body);
$('body > a[href^="/' + set.code + '/"]').each(function () {
console.log(' %s (%s)', $(this).text(), $(this).attr('href'));
});
});
});
}
], function (err, result) {
console.log('ERR');
// result now equals 'done'
});

问题是第二个 waterfall 函数只运行一次,如果我用 each 替换 eachSeries,循环会运行 X 次(但我需要等待结果)。

我错过了什么?

最佳答案

您需要调用eachSeries callback 函数。否则 async 不会知道你已经完成了。 (1)

您还需要告诉 waterfall 函数您已完成该步骤,同样通过调用 callback 函数。 (2)

function (sets, waterfallCallback) {
async.eachSeries(sets, function (set, seriesCallback) {
console.log('SET ' + set.code.toUpperCase());
request(baseurl + set.path, function (err, response, body) {
var $ = cheerio.load(body);
$('body > a[href^="/' + set.code + '/"]').each(function () {
console.log(' %s (%s)', $(this).text(), $(this).attr('href'));
});

seriesCallback(null); /* 1 */

});
}, waterfallCallback /* 2 */);
}

关于javascript - nodejs异步嵌套调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23133590/

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