Erdi
Erdi

Reputation: 1884

Change variable value within async function - node.js

var url = posts.paging.next;
for (var i = 0; i < 3; i++) {
    (function(url,i) {
request(url,{json:true}, function (error, response, body) {
  if (!error && response.statusCode == 200) {
  url = body.paging.next;
  console.log(i+"+++"+url)
  }
});
    })(url,i);
};//for

According to async request response (body.paging.next), İ want to change value of var url which is top of code .Please Help

NOTE: i'm trying to get all comments from facebook api , To do that , i need to get page links . Because of this , i wrote this codes , if you have any other alternative way please suggest them thanx

Upvotes: 0

Views: 960

Answers (1)

mscdex
mscdex

Reputation: 106696

Assuming that you're trying to perform the requests in sequence (e.g. the next request relies on the url from the previous request), you could do something like (using the async module):

var async = require('async');

// ...

var url = posts.paging.next, i = 0;

async.whilst(
  function() { return i < 3; },
  function(callback) {
    ++i;
    request(url, { json: true }, function(err, response, body) {
      // TODO: handle `err`
      //return callback(err);

      if (!err && response.statusCode === 200) {
        url = body.paging.next;
        console.log(i + '+++' + url);
        callback();
      }
    });
  },
  function(err) {
    // done!
  }
);

Upvotes: 1

Related Questions