I'm on Rails and I use Koala in a cron job to import all comments Facebook.
Is it ok to use a for
loop where each time I make a request
and store the response
? Or there is a risk for which the for
restart before I get a response
from Facebook all gets messed up?
In other words: Does the loop wait for the response or do I need a callback function?
Here is the loop:
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
Koala's get_object
call is synchronous, so execution will pause and won't return to your code until the result is ready. (Unless it fails, in which case Koala raises an error).
So yes, it's safe to use like this! The for loop won't continue until the result of the previous call is ready. No callbacks needed!
(I'm basing this on the examples in the Koala wiki).