包含 API 请求的循环是否需要回调?

Is callback needed for loops containing API requests?

我在 Rails,我在 cron 作业中使用 Koala 导入所有评论 Facebook。

是否可以在每次创建 request 并存储 response 时使用 for 循环?或者,在我从 Facebook 获得 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

Koala 的 get_object 调用是同步的,因此在结果准备好之前,执行将暂停并且不会 return 您的代码。 (除非失败,在这种情况下 Koala 会引发错误)。

所以是的,这样使用是安全的!在上一个调用的结果准备好之前,for 循环不会继续。无需回调!

(我基于 Koala wiki 中的示例)。