0

I'm trying to wrap my head around the async library, but I'm pretty wobbly in NodeJs and I can't figure out async.parallel. The code below produces error TypeError: undefined is not a function on the line where the parallel tasks are to be executed. Am I correct in that tasks to be run in async.parallel should have a callback() when they are done? (irrelevant parts of the function are redacted)

function scrapeTorrents(url, callback) {
    request(url, function(err, res, body) {
        if(err) {
            callback(err, null);
            return;
        }
        var $ = cheerio.load(body);
        var results = [];
        var asyncTasks = [];
        $('span.title').each(function(i, element){
            // scrape basic info 
            var show = {title: info.title, year: info.year};
            asyncTasks.push(
                getOmdbInfo(show, function (err, res) {
                    if (res) {
                        omdbInfo = res;
                        results.push({
                            // add basic info and Omdb info
                        });
                    }
                    callback();
                })
            );
        });
        async.parallel(asyncTasks, function(){
            callback(null, results);
        });
    });
}
4

1 回答 1

1

在定义异步任务的部分中,请务必指定一个带有参数方法的闭包,以便在任务完成后调用(命名不同callback以避免提升)。

asyncTasks.push(
    function (done) {
        getOmdbInfo(show, function (err, res) {
            if (err) {
                return done(err);
            }

            if (res) {
                omdbInfo = res;
                results.push({
                    // add basic info and Omdb info
                });
            }

            return done();
        })
    }
 );
于 2015-11-03T01:26:06.660 回答