2

I am using diffbot api along in for loop

this is my code

for (var i = 0; i< 200; i++){
    /* pass url from diffbot */
    console.log("Ready to send Url for parsing to Diffbot ");

    diffbot.article({ uri: url }, function(err, response) {
        if (!err) {
            console.log(i);
        } else {
            console.log("Error Occur in url " + i + "and error is " + err);
            /* need to Add logic for parsing  */
        }
    });
}

Now I got console message like

output is coming 

200 
200
200
200
200

two hundred times.

output is expected 0 to 199

Does any body tell me where I am wrong

Thanks

long.luc
  • 1,191
  • 1
  • 10
  • 30
soccer7
  • 3,547
  • 3
  • 29
  • 50
  • why we need clousure.. Can u please explain – soccer7 Oct 31 '14 at 09:03
  • By the time the statement `console.log(i);` executed, value of `i` is 200, because of asynchronous callback. You need a closure to "keep" the desired value of `i` at the time statement `diffbot.article(...)` executed – long.luc Oct 31 '14 at 09:08

2 Answers2

3

What happens is simple:

Your loop makes 200 posts. The response gets executed for each post asynchronously, meaning that all posts may be done by the time the first response arrives, executing the callback function. Therefore, i==200 by then.

Elaborating a bit after your comment:

You'll need a closure to keep the current value of i by the time you get the response, as stated in fzzle's answer:

 diffbot.article({ uri: url }, (function(i) { 
         return function(err, response) {
         ... }
     })(i)); 

Enclosing your callback function in function(i){ ... } creates the closure. This way, the current value of i is passed to the function, and then available for response with the value you want, whenever this response will come back.

xlecoustillier
  • 16,183
  • 14
  • 60
  • 85
2
 for (var i = 0; i < 200; ++ i) {
     diffbot.article ({ uri: url }, (function (i) { 
         return function (err, response) { ... }
     })(i)); 
 }

This will work.

fzzle
  • 1,466
  • 5
  • 23
  • 28