Reputation: 8977
I'm relatively new to callbacks and have been unsuccessful in getting the following code to work. I have used the async.map function to return the data from each web call to its respective page. However, my console.log(return)
is returning [ , undefined]
even though the console.log(data)
prior to the callback(data)
is returning the web page's html. Here's my code:
var http = require("http"),
fs = require("fs"),
page, chap, ot,
async = require("async");
ot = fs.open('ot.txt', 'w');
page = "test";
chap = 2;
function getData(url, callback) {
var data = "";
var options = {
host: "rs.au.com",
port: 80
}
options.path = url;
console.log("request sent to: http://" + options.host + options.path);
var req = http.request(options, function(res) {
console.log("Response received " + res.statusCode);
res.on('data', function(chunk) {
data += chunk;
});
res.on('end', function(e) {
console.log(data);
callback(e, data);
});
}).end();
}
function main() {
var pathArr = [];
for ( var i = 1; i <= chap; i++ ) {
pathArr[i] = "/".concat(page, "/", i, ".html");
}
async.map(pathArr, getData, function(err, result) {
console.log("The result is :" + result);
});
}
main();
Could anyone please point out why my code is not working and how I can correct it?
Much appreciated!
EDIT: After Brandon Tilley's response I amended the callback function from callback(data)
to callback(e, data)
, however I'm getting no response now from the last console.log
output.
Upvotes: 1
Views: 2218
Reputation: 159105
The Async library assumes your callbacks adhere to the standard Node.js callback signature, which is callback(err, others...)
. Since you are passing data
as the first argument, Async assumes it's an error. You should use callback(e, data)
instead (since e
will be null
in the case of no errors).
[Update]
The other problem is that your array is not correct. Since i
starts at 1 and goes up to chap
, pathArr[0]
is undefined. Change:
pathArr[i] = "/".concat(page, "/", i, ".html");
to
pathArr[i-1] = "/".concat(page, "/", i, ".html");
Upvotes: 2