缺少数组中的元素

时间:2012-11-02 19:45:24

标签: javascript node.js zombie.js

我是Node.js的新手。我正在使用zombie.js从几个网站上抓取一个网页标题。以下是我的代码:

var Browser = require("zombie");
var util = require("util");
halt = require('delayed');
title = [];
url = [ 'http://www.apple.com', 'http://www.microsoft.com', 'http://www.dell.com' ];


function getTitles(url){
    //console.log('Start scraping title');
    var length = url.length;
    console.log('Total Site to Scrape: '+length);
    label = 1;
    for(var i=0;i<length;i++){
        browser = new Browser()
        browser.runScripts = false
        browser.setMaxListeners(0);
        browser.visit(url[i], function(e, browser, status, errors) {
        browser.wait(function(){
            title[i] = browser.text('html > head > title');
            console.log(label+': '+title[i]);
            browser.close();
            label++;
        });
        });
    };  
}


getTitles(url);

halt.delay(function () {
    console.log('Array Length: '+title.length)
    console.log('Array Content: '+title)
}, 10)

以下是代码的输出:

Total Site to Scrape: 3
1: Apple
2: Dell Official Site - The Power To Do More | Dell
3: Microsoft Home Page | Devices and Services
Array Length: 4
Array Content: ,,,Microsoft Home Page | Devices and Services

我不理解的部分:

  1. 为什么数组长度返回4而不是3?只有 三个网址
  2. 为什么数组内容只返回最后一个元素?其他两个缺失的元素在哪里?

1 个答案:

答案 0 :(得分:1)

我不熟悉僵尸,但我很确定这是一个关闭问题。当你认为i时,{{1}}并不是你想象的那样。有关闭包的一些信息,请参阅此答案:JavaScript closure inside loops – simple practical example。基本上正在发生的事情是你的循环继续,即使你的请求是异步的,他们没有这样做,当他们回来时,你已经循环所有3个URL,现在你有三个元素......然后它插入所有3值到第4个元素。最后一个获胜,所以微软就是你所看到的。