首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >EventMachine暂停以等待响应

EventMachine暂停以等待响应
EN

Stack Overflow用户
提问于 2011-03-27 04:04:04
回答 1查看 857关注 0票数 2

好的,我有代码,在引擎盖下使用Cramp\Tramp => EventMachine。代码:

代码语言:javascript
复制
class RetrieveController < ApplicationController
  on_start :retrieve_messages

#nonimportant stuff


def receive_messages
  #other stuff
  @current_user = false  
  User.where(User[:id].eq("request.env['rack.session']['user_id']")).all method(:retrieve_current_user)
  if wait_for_current_user
    EM.add_periodic_timer(1) {wait_for_current_user}
  else
    render @current_user
    finish
  end
 end

 def wait_for_current_user
   if @current_user
     render "current_user is set"
     true
   else
     render "waiting for current_user"
     false
   end
 end

 def retrieve_current_user(users)
   users.each do |user|
     @current_user = user.name
   end
 end

end

我需要查询的结果才能在控制器操作中继续执行,但看起来在我获得数据之前执行已经结束。呈现的文本为:

正在等待current_user false

我的gemfile是:

代码语言:javascript
复制
source 'http://rubygems.org'

gem 'cramp', '~> 0.12'
gem 'tramp', '~> 0.2'

gem 'activesupport', '3.0.4'
gem 'rack', '~> 1.2.1'
gem 'eventmachine', '~> 0.12.10'

gem 'usher', '~> 0.8.3'
gem 'thin', '~> 1.2.7'
gem "bcrypt-ruby", :require => "bcrypt"
EN

回答 1

Stack Overflow用户

发布于 2012-03-14 03:55:43

我还没有使用Cramp/Tramp,所以如果我的假设是错误的,很抱歉,但根据我所能理解的情况,以下是正在发生的事情:

代码语言:javascript
复制
def received_messages
  # other stuff
  # we set @current_user to false <-- this is important
  @current_user = false
  # we are using tramp (async orm) this is not going to block the execution
  # of this method, so we will start executing this but we will also proceed
  # to the next step in this method (if statement after this)
  User.where(User[:id].eq("request.env['rack.session']['user_id']")).all method(:retrieve_current_user)
  # So the query is starting its execution but we are already at this if
  # statement and we execute the "wait_for_current_user" method and at this
  # point of time @current_user is still set to false <--- because of that
  # your wait_for_current_user method is printing "waiting for current user"
  # AND it returns false to this if statement <--- because of that we DO NOT
  # add the periodic timer (maybe change if to unless)
  if wait_for_current_user
    # we do not enter here because the wait_for_current_user returned false
    EM.add_periodic_timer(1) {wait_for_current_user}
  else
    # we go here and we execute "render false" which simply prints "false"
    render @current_user
    # at this point the query started on the User model might still be
    # running but here we go and execute the finish command and all you
    # get is "waiting for current_user false"
    finish
  end

问题出在你的方法的条件中。我很抱歉没有给出你的代码的修复版本,但希望你现在可以自己找出它,因为你知道错误在哪里。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5444962

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档