Here is how I could solve the problem.
#!/usr/bin/env node var http = require('http'); var argv = process.argv.splice(2), truecount = argv.length, pages = []; function printUrls() { if (--truecount > 0) return; for (i = 0; i < pages.length; i++) { console.log(pages[i].data + '\n\n'); } } function HTMLPage(url) { var _page = this; _page.data = '### [URL](' + url + ')\n'; http.get(url, function(res) { res.setEncoding('utf8'); res.on('data', function(data) { _page.data += data; }); res.on('end', printUrls); }); } for (var i = 0; i < argv.length; i++) pages.push(new HTMLPage(argv[i]));
It adds queries to the array at the beginning of each query, so once this is done, I can iterate well through the answers, knowing that they are in the correct order.
When working with asynchronous processing, I find it much easier to think of each process as something specific beginning and end. If you want the order of the queries to be preserved, a record must be made at the creation of each process, and then you will return to that record at the end. Only then can you ensure that you have things in the correct order.
If you were desperate to use your method above, then you can define a variable inside your get callback closure and use this to store URLs, so you wonβt get the last URL rewriting your variables. If you all go this way, you will significantly increase your overhead when you have to use your process.argv urls to access each answer in that order. I would not recommend this.
Lawrence jones
source share