//二.采集目标内容的地址
$.each(one_url,function(i,v){
var temp = v.split('-')
temp[1] = 2
console.log('a')
async.series([
function(){
n.get(temp.join('-'),{decode_response:false,encoding:'binary',follow:1},list_url)
}
])
console.log('ccccc')
})
//二。采集分类列表的链接地址
var list_url = function(error,response,body){
var content = new iconv('gbk','UTF-8//TRANSLIT//IGNORE').convert(new Buffer(body,'binary')).toString()
console.log($(content).find('.last').attr('href'))
}
日志中输出
C:\nodejs\node.exe cj39.js
a
ccccc
a
ccccc
a
ccccc
a
ccccc
a
ccccc
a
ccccc
a
ccccc
a
ccccc
a
ccccc
a
ccccc
a
ccccc
a
ccccc
a
ccccc
a
ccccc
a
ccccc
a
ccccc
a
ccccc
undefined
/browse/313-2-2188.html
/browse/23-2-893.html
/browse/14440-2-2188.html
/browse/320-2-2188.html
/browse/322-2-2188.html
undefined
/browse/19018333-2-2188.html
/browse/3157-2-2188.html
/browse/3162-2-2188.html
/browse/323-2-2188.html
/browse/309-2-2188.html
/browse/3166-2-2188.html
/browse/311-2-2188.html
/browse/3163-2-2188.html
/browse/27-2-2188.html
/browse/271-2-2188.html
可以看到async里面没有等待函数执行完成就执行了日志console.log(‘ccc’)的输出。求怎么按顺序执行?
6 回复
urls = ['http://aaaaa....', 'http://bb....'];
async.each(urls, function(url, callback){
// do the fetch work
fetch_url_content(url, callback);
], function(results) {
console.log("Fetch results:");
results.forEach(function(item, i) {
console.log(urls[i], ':');
console.log(item);
});
})
这是 async.map
的正确用法:
var array = [0, 1, 2, 3];
async.map(array, function (item, callback) {
console.log("Transforming item: " + item);
var transformed = item + 1;
callback(null, transformed);
}, function (error, results) {
console.log(results); // => [1, 2, 3, 4]
});
楼主可能对非阻塞模型和 callback
的语法地位都不理解,建议先学点入门的东西再写代码……