2014-01-29 50 views
0

嘗試使用Node.js的爲什麼我的offset變量的值保持爲零

var request = require('request'); 
var fs = require('fs'); 
var apiKey = 'my-key-here'; 
var offset = 0; 

for (var i=0; i<5; i++) { 
    console.log('request #' + i + '...'); 

    var requestURL = 'http://api.tumblr.com/v2/blog/blog.tumblr.com/posts/text?api_key=' 
    + apiKey 
    + '&offset=' 
    + offset; 

    console.log(requestURL); 

    request(requestURL, function(error, response, body) { 
    if (!error && response.statusCode == 200) { 
     var resultAsJSON = JSON.parse(body); 
     resultAsJSON.response.posts.forEach(function(obj) { 
     fs.appendFile('content.txt', offset + ' ' + obj.title + '\n', function (err) { 
      if (err) return console.log(err); 
     }); 
     offset++; 
     });  
    } 
    }); 
} 

默認情況下,做一個簡單的tumblr刮刀,該API只返回一個最大的20個最新的帖子。我想要抓住所有的帖子。作爲測試,我想先獲得最新的100個,因此在循環聲明中獲得i<5

這樣做的竅門是使用offset參數。例如,給定一個值爲20的offset,API不會返回最新的20,而是返回從頂部21開始的帖子。

因爲我不能確定API會一直返回20個帖子,所以我使用offset++來獲得正確的偏移號碼。

上面的代碼工作,但console.log(requestURL)返回http://api.tumblr.com/v2/blog/blog.tumblr.com/posts/text?api_key=my-key-here&offset=0 五次。

所以我的問題是,爲什麼我的requestURL中的offset值仍然爲0,即使我已經添加了offset++

+0

不是這個。您啓動一個請求,並期望它在循環進入下一次迭代之前完成。這些請求甚至在循環完成之後纔開始,這就是爲什麼'offset'對所有這些都是零的原因。你需要一個異步的for-each循環。 –

+0

事情是我正在'appendFile'中寫入'offset'變量,並且它們在0到99的文本文件中正確顯示。 – hfz

+0

這只是由於以相同順序發生的請求回調但不能保證,你不應該依賴它。 –

回答

1

您應該在循環中增加offset,而不是在回調中。回調僅在請求完成後觸發,這意味着您在offset = 0的範圍內發出五個請求,並在收到回覆後遞增。

var requestURL = 'http://api.tumblr.com/v2/blog/blog.tumblr.com/posts/text?api_key=' 
    + apiKey 
    + '&offset=' 
    + (offset++); // increment here, before passing URL to request(); 

編輯: 要20在每個迭代偏移,並使用回調偏移:再次

for (var i=0; i<5; i++) { 
var offset = i * 20, requestURL = 'http://api.tumblr.com/v2/blog/blog.tumblr.com/posts/text?api_key=' 
    + apiKey 
    + '&offset=' 
    + offset; 

    (function(off){ 
     request(requestURL, function(error, response, body) { 
      if (!error && response.statusCode == 200) { 
       var resultAsJSON = JSON.parse(body); 
       resultAsJSON.response.posts.forEach(function(obj) { 
        fs.appendFile('content.txt', off + ' ' + obj.title + '\n', function (err) { 
         if (err) return console.log(err); 
        }); 
        off++; 
       });  
      } 
     }); 
    }(offset)); // pass the offset from loop to a closure 
} 
+0

雖然'i'和'offset'有區別。 'offset'必須是要跳過的帖子的數量,而'i'是我想要使用API​​的次數。 1個API調用一次最多可以發佈20個帖子。 – hfz

+0

但是在你的問題中,你在每次迭代中增加一個偏移量,所以我假定了'offset == i'。那麼使用'offset = i * 20'。 – pawel

+0

'offset ++'在'forEach'範圍內,它迭代了API返回的所有帖子。所以我正在計算那裏的帖子。 – hfz

相關問題