2016-11-01 48 views
0

我在Rails上,我在一個cron工作中使用考拉來導入所有評論Facebook。包含API請求的循環是否需要回調?

可以使用for循環,每次我做一個request並存儲response?或者在我得到之前重新啓動for的風險都會被搞砸了嗎?

換句話說:循環等待響應還是需要回調函數?

這裏是循環:

def self.import_comments 
    # Access Facebook API 
    facebook = Feed.get_facebook_access 

    # Run 190 queries per cron job 
    for i in 1..190 

     id_of_latest_feed   = Feed.get_latest['fb_id'] 
     id_of_latest_feed_checked = Option.get_feed_needle 

     # Check if there are more recent feeds than the latest checked 
     if id_of_latest_feed != id_of_latest_feed_checked 
      # Get the facebook id of the feed which comes after the latest checked 
      latest_feed_checked = Feed.where(fb_id: id_of_latest_feed_checked).first 
      this_date   = latest_feed_checked['fb_updated_time'] 
      feed_to_check  = Feed.get_older_than(this_date) 

      unless feed_to_check.nil? 
       # Get the ID of the feed to check 
       fb_id = feed_to_check['fb_id'] 
       # Update needle 
       Option.update_feed_needle_to(fb_id) 

       # -------- REQUEST! --------- # 
       # Get comments from Facebook 
       @comments = facebook.get_object("#{ fb_id }/comments?filter=stream") 

       # Save each comment 
       @comments.each do |comment| 
        if Comment.exists?(fb_id: comment['id']) 
         # don't do anyhting 
        else 
         # save the comment 
        end 
       end 
      end 
     end 
    end 
end 

回答

0

考拉的get_object調用是同步的,所以執行將暫停,直到結果準備好將不會返回到您的代碼。 (除非它失敗,在這種情況下考拉提出錯誤)。

所以,是這樣使用的安全! for循環將不會繼續,直到前一個調用的結果準備就緒。無需回傳!

(我正在基於Koala wiki中的例子)。

+0

我一直在運行代碼,目前沒有問題,所以我想你是對的 –