0

I'm attempting to increment a variable by utilizing data returned in the response of an http GET request. I declare a variable globally with var nextTimestamp, grab data from the http response with nextTimestamp = images[0].created_time, and then attempt to increment minTimestamp by placing minTimestamp = nextTimestamp just outside the close of my http request. Problem is, outside of the response, nextTimestamp keeps coming back as undefined. Relevant Node server code is below:

var minTimestamp = 1419656400;
var nextTimestamp;

request('https://api.instagram.com/v1/media/search?lat=40.8296659&lng=-73.9263128&distance=250&min_timestamp=' + minTimestamp + '&client_id=CLIENT-ID',
    function (error, response, body) {
      if (error) { 
        console.log('error');
        return;
      }

      //JSON object with all the info about the image
      var imageJson = JSON.parse(body);
      var images = imageJson.data;
      nextTimestamp = images[0].created_time;
      var numImages = images.length;

      async.eachSeries(images, function(image, callback) {

        //Save the new object to DB
        Event.findOneAndUpdate( { $and: [{latitude: '40.8296659'}, {radius: '250'}] }, { $push: {'photos':
          { img: image.images.standard_resolution.url,
            link: image.link,
            username: image.user.username,
            profile: image.user.profile_picture,
            text: image.caption ? image.caption.text : '',
            longitude: image.location.longitude,
            latitude: image.location.latitude
          }}},
          { safe: true, upsert: false },
          function(err, model) {
            console.log(err);
          }
        );
        callback();
      }, function(err){
           // if any of the image processing produced an error, err would equal that error
           if( err ) {
             // One of the iterations produced an error.
             // All processing will now stop.
             console.log('Image failed to process');
           } else {
             console.log('Images processed');
       }
         });
       }
      );
   minTimestamp = nextTimestamp;
MattDionis
  • 3,534
  • 10
  • 51
  • 105

1 Answers1

1

The second argument of the function 'request' is a callback that is executed asyncronously. Long story short, it will only be executed after your last line of code

minTimestamp = nextTimestamp;

That's why 'nextTimestamp' is undefined. It hasn't been set yet. And this is not a matter of how quickly the 'request' function will execute your callback function. The last assignment expression will be added to the stack and resolved before that callback - always.

If you want to use nextTimestamp after it has been set, you have to do it inside the callback, somewhere after

nextTimestamp = images[0].created_time;

For instance, if you want to use 'nextTimestamp' to do another 'request' where the url querypart value for 'min_timestamp' equals 'nextTimestamp' you can do it like this

function myAsyncRequest(url, callback) {
  request(url, function(error, response, body) {
    ...
    callback(nextTimestamp);
    ...
  }
}

var minTimestamp = 1419656400;
myAsyncRequest('https://api.instagram...' + minTimestamp + '...', function(nextTimestamp) {
  //...
  myAsyncRequest('https://api.instagram...' + nextTimestamp + '...', function(nextTimestamp) {
    //...
  });
  //...
});

Here you are passing your nextTimestamp using a callback function and waiting for the async function to execute and set it before using it.

filipe
  • 1,641
  • 1
  • 9
  • 8
  • I'm confused as to why the callback for my 'request' function is called after `minTimestamp = nextTimestamp;` because this line sits outside of the entire 'request' function's scope. – MattDionis Jan 13 '15 at 20:17
  • 1
    It's not a matter of what comes first. The callback is not executed right away. The callback is a function definition (not a call) that will be executed by the function request, when it has finished to send the request and get the response back or failed and get an error. – filipe Jan 13 '15 at 20:33