Move flow control logic into its own function

Change-Id: Iab3e1afdee4666ff3ea07cdda06445d1f9933df3
Reviewed-on: http://review.couchbase.org/39176
Reviewed-by: Chiyoung Seo <chiyoung@couchbase.com>
Tested-by: Michael Wiederhold <mike@couchbase.com>