gpt4 book ai didi

ruby - EventMachine 暂停等待响应

转载 作者:太空宇宙 更新时间:2023-11-03 16:37:38 24 4
gpt4 key购买 nike

好的,我有代码在后台使用 Cramp\Tramp => EventMachine。代码:

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

我需要查询的结果才能在 Controller 操作中继续执行,但看起来执行在我获取数据之前就已完成。呈现的文本是:

等待当前用户 假的

我的 gemfile 是:

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"

最佳答案

我没有使用过 Cramp/Tramp,如果我的假设不正确,我深表歉意,但根据我的理解,这是正在发生的事情:

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

问题出在您的方法中。很抱歉没有提供您的代码的固定版本,但希望您现在可以自己弄明白,因为您知道错误出在哪里。

关于ruby - EventMachine 暂停等待响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5444962/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com