I'm trying to use async's each function to call the abc function, and I am running into a couple problems. The code is as follows.
The reason why I am using the for loop here is because when I tried to use each function, the url that's passed into the abc function's url is in the form of array instead of string. So I'm wondering if there's any other way to clear this up without having to add the for loop.
After adding a couple print statements, I realized that the code never executes pass http.get(url[a], newFileLoc, function (error, result){ for some reason. There's always an error message "async.each(urls, downloadFile(urls, function(){ TypeError: Object # has no method 'each'"
So I guess my real question is, what exactly is wrong with the code? I tried to use forEach instead of each, but there was still another error "iterator(x, function (err) { TypeError: undefined is not a function".
Someone please help out!!!
var abc = function ( url, cb ) {
for (var a = 0; a < url.length; a++){
var index = url[a].lastIndexOf("/") + 1;
var filename = url[a].substr(index);
var newFileLoc = "./tmp/" + filename;
http.get(url[a], newFileLoc, function (error, result) {
if (error) {
console.error(error);
} else {
cb();
}
});
}
}
var urls = ["www.randomurl.random.random/", "www.randomurl.random.random/"];
async.each(urls, abc(urls, function(){
console.log('downloaded' + results);
}), function(err){
if(err){
console.log(err);
}
});
The signature of each is each(arr, iterator, callback), but on the iterator place, you are calling abc directly and it doesn't return a function.
A fix of that issue leads to:
async.each(
urls,
abc,
function(err) {
if(err){
console.log(err);
};
}
);
Also note that trying to call console.log causes IE9 and up to crash your script.
...and please clean up the indentation. The code is very hard to read when the opening and closing braces don't follow The One True Brace style (which is what is common for JavaScript).