This question already has answers here:
How to return value from an asynchronous callback function? [duplicate]
                            
                                (3个答案)
                            
                    
                5年前关闭。
        

    

我试图通过利用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;

最佳答案

函数“ request”的第二个参数是异步执行的回调。长话短说,它只会在您的最后一行代码之后执行

minTimestamp = nextTimestamp;


这就是为什么'nextTimestamp'未定义的原因。尚未设置。这与“ request”函数执行回调函数的速度无关。最后一个赋值表达式将添加到堆栈中,并在该回调之前解析-始终如此。

如果要在设置nextTimestamp之后使用它,则必须在回调内部的某个位置

nextTimestamp = images[0].created_time;


例如,如果您要使用“ nextTimestamp”执行另一个“请求”,其中“ min_timestamp”的url querypart值等于“ 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,并在使用异步函数之前等待异步函数的执行和设置。

关于javascript - Node.js响应中的变量作用域,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27929952/

10-09 17:27