【问题标题】:nodejs async nested callsnodejs异步嵌套调用
【发布时间】:2014-04-17 21:14:39
【问题描述】:

我想废弃一个网址:

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

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

我错过了什么?

【问题讨论】:

    标签: javascript node.js asynchronous


    【解决方案1】:

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

    您还需要通过调用callback 函数告诉waterfall 函数您已完成该步骤。 (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 */);
    }
    

    【讨论】:

    • 效果很好,但没有第二次回调(我不明白你为什么要在那里使用回调)。当我在每个系列上放置一个回调时,它告诉我回调未定义(无函数)
    • 我已经修改了答案以更好地解释两个不同的回调。如果没有第二个,最后一个函数将永远不会运行。 (带有console.log('ERR');// result now equals 'done' 的那个)
    猜你喜欢
    • 1970-01-01
    • 2018-06-04
    • 1970-01-01
    • 1970-01-01
    • 2016-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-15
    相关资源
    最近更新 更多