Nodejs响应中的变量范围

时间:2015-01-13 19:25:07

标签: javascript node.js asynchronous httpresponse

我试图通过利用http GET请求响应中返回的数据来增加变量。我使用var nextTimestamp全局声明变量,使用nextTimestamp = images[0].created_time从http响应中获取数据,然后将minTimestamp放在我的http请求结束之外,尝试增加minTimestamp = nextTimestamp 。问题是,在回复之外,nextTimestamp会一直以undefined的形式返回。 相关的节点服务器代码如下:

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;

1 个答案:

答案 0 :(得分:1)

函数的第二个参数' request'是一个异步执行的回调。简而言之,它只会在你的最后一行代码之后执行

minTimestamp = nextTimestamp;

这就是为什么' nextTimestamp'未定义。它尚未设定。这不是“请求”的快速程度问题。函数将执行您的回调函数。最后一个赋值表达式将被添加到堆栈中并在该回调之前解析 - 总是。

如果你想在设置后使用nextTimestamp,你必须在回调中进行,在

之后的某个地方
nextTimestamp = images[0].created_time;

例如,如果您想使用' nextTimestamp'做另一个请求'其中url querypart值为' min_timestamp'等于' nextTimestamp'你可以这样做

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) {
    //...
  });
  //...
});

在这里,您将使用回调函数传递nextTimestamp并等待异步函数执行并在使用之前进行设置。