Quantcast
Channel: CNode:Node.js专业中文社区
Viewing all articles
Browse latest Browse all 14821

新手求助:很简单的问题让我很疑惑,这个问题是因为异步执行的原因吗

$
0
0

下面两段代码主要的不同在于for( var i=0;i<topicUrls.length;i++){console.log(topicurls[i])}的不同

# 代码一
var cheerio = require('cheerio');
var superagent = require('superagent');
var url = require('url');
var async = require('async');

var cnodeUrl = 'https://cnodejs.org/';
var topicUrls = [];
superagent.get(cnodeUrl)
   .end(function(err,res){
      if(err){
        return console.error(err);
      } 
	  
      var $ = cheerio.load(res.text);
	  
      $('#topic_list .topic_title').each(function(idx,element){
          var $element = $(element);
	  var href = url.resolve(cnodeUrl,$element.attr('href'));
	  topicUrls.push(href);
      });
    });

for (var i=0;i<topicUrls.length;i++){
   console.log(topicUrls[i]);
}

# 代码二
var cheerio = require('cheerio');
var superagent = require('superagent');
var url = require('url');
var async = require('async');

var cnodeUrl = 'https://cnodejs.org/';

superagent.get(cnodeUrl)
   .end(function(err,res){
      if(err){
        return console.error(err);
      }
     var topicUrls = [];      
      var $ = cheerio.load(res.text);

      $('#topic_list .topic_title').each(function(idx,element){
          var $element = $(element);
	  var href = url.resolve(cnodeUrl,$element.attr('href'));
	  topicUrls.push(href);
      });

      for(var i=0;i<topicUrls.length;i++){
        console.log(topicUrls[i]);
      }

    });


‘代码一‘和’代码二’为什么会有这么大的不同,‘代码一’不能正常抓取页面,而‘代码二’可以?

请师傅们不吝赐教,在下不胜感激


Viewing all articles
Browse latest Browse all 14821

Trending Articles