在使用大量异步代码时,我对如何编写体面的代码感到困惑。
在以下代码片段中,我登录以获取身份验证 cookie,并将该 cookie 用于下一个请求以获取项目名称列表(例如):
def self.populateProjectsTable(projects_controller)
payload = {email: "email", password: "pass"}
HTTP.post("http://example.com/login", {payload: payload}) do |response|
authCookie = response.headers['Set-Cookie']
HTTP.get("http://example.com/projects.json", {cookie: authCookie}) do |response|
projects = JSON.parse(response.body.to_str)
projects_controller.projects = projects
projects_controller.reloadData
end
end
end
虽然这会起作用,但代码感觉很脏。没有真正遵循单一责任原则。我想用几种方法提取它:
def self.populateProjectsTable(projects_controller)
@taskList = TaskList.new
@taskList.doLogin
projects = @taskList.getProjects
projects_controller.projects = projects
projects_controller.reloadData
end
def doLogin
payload = {email: "email", password: "pass"}
HTTP.post("http://example.com/login", {payload: payload}) do |response|
@authCookie = response.headers['Set-Cookie']
end
end
def getProjects
HTTP.get("http://example.com/projects.json", {cookie: @authCookie}) do |response|
projects = JSON.parse(response.body.to_str)
end
end
这显然是行不通的。该getProjects
方法在doLogin
完成之前调用,并且项目仅在块范围内已知,而不会将数据返回给该populateProjectsTable
方法。
如果没有第一个示例中所示的嵌套,如何编写此类应用程序?