Skip to content

Instantly share code, notes, and snippets.

@wuqian
Created September 11, 2012 07:58
Show Gist options
  • Save wuqian/3696785 to your computer and use it in GitHub Desktop.
Save wuqian/3696785 to your computer and use it in GitHub Desktop.
node async模块 waterfall+queue使用
var async = require('async');
var http = require('http');
function getPage(callback) {
http.get('http://www.baidu.com', function(res) {
var buffers = [];
var size = 0;
res.on('data', function(buffer) {
buffers.push(buffer);
size += buffer.length;
});
res.on('end', function() {
var buffer = new Buffer(size);
var pos = 0;
for (var i = 0; i < buffers.length; i++) {
buffers[i].copy(buffer, pos);
pos += buffers[i].length;
}
callback(null, buffer);
});
});
}
function printPage(buffer, callback) {
console.log(buffer.toString());
callback(null, 'done');
}
var q = async.queue(function (task, callback) {
//console.log('hello ' + task.name);
async.waterfall([getPage, printPage], function(err, results) {
callback();
});
}, 2);
// assign a callback
q.drain = function() {
console.log('all items have been processed');
};
q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function (err) {
console.log('finished processing bar');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment