0

New to node, my understanding so far is that a callback function will only be ran when the current function is complete? Do I have that right?

Im trying to scrape the first 3 results from a bing search, increment i and then run again but the console is logging "calling back" and executing the second loop before the browser has even launched.

Any suggestions on the best way to get this working would be appreciated.

function browse(rows, i, cb) {
  var asn = rows[i].id
  var name = rows[i].name
  console.log(name);
  client
    .url('https://www.bing.com')
    .setValue('#sb_form_q', '"' + name + '"')
    .click('#sb_form_go', function() {
      for (var i = 1; i < 4; i++) { //get first 3 results
        var loc = '#b_results > li:nth-child(' + i + ') > h2 > a';
        client.getAttribute(loc, 'href', function(err, text) {
          console.log(text);
          fs.appendFile("asnres.txt", asn + ":" + text + "\n", function(err) {
            if (err) {
              return console.log(err);
            }
          });
        });
      }
    });
  if (i != rows.length) {
    console.log("calling back");
    i++
    cb(rows, i)
  }
}

client.init().then(function() {
  browse(rows, i, browse)
});
Sam
  • 161
  • 1
  • 14
  • callback is run when you call it. – webduvet Aug 12 '15 at 12:00
  • very helpful thankyou, so how do i block until everything else has finished? – Sam Aug 12 '15 at 12:07
  • 1
    Function calls in for loop are never synchronous. The moment the for loop has function calls, it becomes async. You need to manage the function calls accordingly. Check out http://stackoverflow.com/questions/30072629/make-function-calls-in-for-loop-synchronous – Paritosh Aug 12 '15 at 12:10
  • Thank you Parotish this looks like exactly what I need :) – Sam Aug 12 '15 at 12:24
  • Though it may be useful, you should never make async work like sync. Try to optimise through the callback architecture. – Paritosh Aug 12 '15 at 13:14

0 Answers0