Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/38.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript async.each和http get_Javascript_Node.js_Asynchronous - Fatal编程技术网

Javascript async.each和http get

Javascript async.each和http get,javascript,node.js,asynchronous,Javascript,Node.js,Asynchronous,我想通过编程从多个URL获取元标记,并用于进一步处理。 我正在使用下面的代码片段,这个片段总是只打印第一个URL元标记,而异步回调res是未定义的。我是否缺少异步的任何东西 var http = require('http'), cheerio = require('cheerio'), async = require('async'), urls = [ "http://theatlantic.com", "http://nytimes.

我想通过编程从多个URL获取元标记,并用于进一步处理。 我正在使用下面的代码片段,这个片段总是只打印第一个URL元标记,而异步回调res是未定义的。我是否缺少异步的任何东西

var http = require('http'),
    cheerio = require('cheerio'),
    async = require('async'),
    urls = [
        "http://theatlantic.com",
        "http://nytimes.com"
    ];

    function test() {
    var $, data = '';

    getMetaData = function(uri, callback) {
        http.get(uri, function(resp) {
            console.log('Fetching Url:' + uri);

            resp.on('data', function (chunk){
                data += chunk;
            });

            resp.on('end', function () {
                $ = cheerio.load(data);
                console.log('Meta Tag:' + $('meta[property="og:description"]').attr('content') + '\n'); //use for furthur processing
                callback(null, $('meta[name="description"]').attr('content'));
            });
        });
    }

    async.each(urls, getMetaData, function(err, res) {
       console.log(res);
    });
};

test();

将“var data”移动到getMetaData中,否则所有线程都将写入同一个变量中……它起作用了。但是回调中的“res”是空的,而不是元描述。根据文档,这是正确的:
迭代器被传递一个回调(err),一旦完成就必须调用它。如果没有发生错误,则应在没有参数或显式空参数的情况下运行回调。
。另外:您对控制台日志使用
og:description
,对回调使用
description
。。。可能是这样吗?