0

I think I am using asynchronous functions in a completely wrong way, and need some help.

I want my function to:

  • Scan an array of objects

  • Test the "Name" value of each object against a regular function; make a http request (ie, "www.foobar.com/"+array.Name) using request, returns 1 if source does exist.

  • If both these conditions are true, add object to a new array

  • When array is fully scanned, save the new array into a file

It all works; however, the asynchronous calls finish running AFTER the file is written!

Example:

function checkName(foo) {

  request("www.foobar.com/"+foo, function(error, response, body) {
    if (!error && response.statusCode == 200)
      return 1;
    else
      return 0;
  });

}

function checkSrc(foo) {
  for (var i = 0; i < 10; i++) {
      if (!(banlist.test(foo[i].name)) && checkName(foo[i].name)) {
        str.push(foo[i]);
      }
      count++;
  }
}

Here begins the actual execution: I read the source file, want to populate 'data' with the array created by 'checkSrc', then save it to a file.

As I said above the requests finish after the file is saved, thus I have an empty array in the final object.

fs.readFile('./data.js', function read(err, data) {
  if (!err) {

    console.log("Response received!");

    var dump = JSON.parse(data);

    var len = dump.applist.apps.length;

    var str = [];

    console.log("Parsing...");

    checkSrc(dump.list);

    var final = {

      "list": str

    };

    str_final = JSON.stringify(final);



    fs.writeFile("parsed.js", str_final, function(err) {
      if (err) {
        return console.log(err);
      }

    });
  };

});

I have found some similiar questions here in stackoverflow, but none of them make http requests; I have tried to wrap my cycle into a function, but it did not work either. I have tried using the request-sync and sync-request node modules, but seem to be deprecated.

Ferduun
  • 137
  • 13
  • Since you have a loop, this may help you more: https://stackoverflow.com/search?q=[nodejs]+loop+async . Questions like this are asked very often, so I would be surprised if you don't find any existing question about this. – Felix Kling Oct 13 '15 at 14:19
  • 1
    I wanted to write an answer, but ok, it will be just a comment: your function `checkName` returns `undefined` before the request even starts. You need to start `n` requests and after whichever completes ass values to the array. Return value of the callback goes to the function that called that callback, which is HTTP library. – Tomáš Zato Oct 13 '15 at 14:19
  • Didn't know about the return part, thanks; with the second part you mean tat the checkName function should send values directly to the array? – Ferduun Oct 13 '15 at 14:43

0 Answers0