It can fulfill the requirements, but fault tolerance, expansion and readability are a mess
request+bluebird version
var request = require('request');
var Promise = require('bluebird');
var prequest = Promise.promisify(request);
var args = process.argv;
if(args.shift() === 'node') args.shift();
if(process.argv.length !== 3) {
console.log('must input 3 url, got', args);
process.exit();
}
Promise.all(args.map(function(url) {
return prequest(url);
}))
.each(function(result) {
var response = result[0];
console.log(response.request.href, response.body);
})
.catch(function(e) {
console.error(e);
});
The title doesn’t say whether the request is parallel or serial. It’s all parallel here. If it’s serial, just keep the order and print with your eyes closed.
Usually when I encounter this kind of situation, I will decisively choose to write callbacks. The code probably looks like the following:
var http = require("http"),
urls = process.argv,
datas = [];
if( urls.shift() === "node" ) urls.shift();
function getHTML( url, callback ) {
http.get( url, function( res ) {
var result = "";
res.on( "data", function(chunk) { result += chunk; })
.on( "end", function() { callback( result ); });
})
}
(function get( p ) {
if( p === urls.length ) return last();
getHTML( urls[p], function(res) {
datas.push( res )
get( ++p );
})
function last() {
datas.forEach(function(d){ console.log(d) })
}
})(0);
But since I came into contact with Promise, I feel that writing asynchronously this way is much smoother, so I gradually changed it. The code probably looks like this:
var Promise = require("promise").Promise,
http = require("http");
var urls = process.argv;
if( urls.shift() === "node" ) urls.shift();
function getHTML( url ) {
return new Promise(function( resolve, reject ) {
http.get( url, function( res ) {
var result = "";
res.on( "data", function(chunk) { result += chunk })
.on( "end", function() { resolve(result) })
.on( "error", function() { reject(result) })
})
})
}
urls.map(getHTML).reduce(function(seq, html) {
return seq.then(function(){return html}).then(function(res){
console.log( res );
})
}, Promise.resolve());
The native version uses two variables, results and counter, to maintain the state, and maintain the order by relying on the idx variable
It can fulfill the requirements, but fault tolerance, expansion and readability are a mess
request+bluebird version
The title doesn’t say whether the request is parallel or serial. It’s all parallel here. If it’s serial, just keep the order and print with your eyes closed.
Usually when I encounter this kind of situation, I will decisively choose to write callbacks. The code probably looks like the following:
But since I came into contact with Promise, I feel that writing asynchronously this way is much smoother, so I gradually changed it. The code probably looks like this: