来自以下指南:http://krondo.com/blog/?p=1682
Deferreds help us avoid one of the pitfalls we identified with callback programming. When we use a deferred to manage our callbacks, we simply can’t make the mistake of calling both the callback and the errback, or invoking the callback twenty-seven times. We can try, but the deferred will raise an exception right back at us, instead of passing our mistake onto the callbacks themselves
谁能给我一个更好的解释?
我注意到它无论如何都不起作用,因为在本教程的大多数情况下,结束回调也会调用 reactor.stop()。 但是为什么调用 deferred 两次没有意义呢?为什么它与再次调用一系列方法有什么不同?
最佳答案
Deferred
表示可能可用(现在或将来)但现在不一定可用的请求结果。
结果流通过Deferred
,通过它们的回调链。例如,在一个同步程序中,你可能有这样的东西:
response_bytes = make_request(...)
response_dict = parse_json(response_bytes)
response_object = construct_object(response_dict)
return response_object.method()
转换为返回 Deferred
的代码,这是:
response_bytes_later = make_request_async(...)
response_dict_later = response_bytes_later.addCallback(parse_json)
response_object_later = response_dict_later.addCallback(construct_object)
return response_object_later.addCallback(lambda response_object:
response_object.method())
询问为什么不能触发(或“回调”)由 make_request_async
返回的 Deferred
类似于询问为什么不能有 make_request
return 多次导致重新发出请求。如果你想在同步版本中再次发出请求,你必须再次调用make_request
(并得到一个新的结果)。如果你想在异步版本中再次发出请求,你必须再次调用make_request_async
(并得到一个新的Deferred
)。
关于python - 为什么我们不能两次调用 Twisted 延迟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23639392/