我想了解如何inlineCallbacks
使異步代碼看起來像同步碼的工作,我現在用的是Twisted's實現作爲參考這裏爲什麼Twisted的inlineCallbacks返回「延遲」對象
正常功能:?。輸入→輸出
inlineCallbacks
裝飾發生器功能:輸入→遞延
它給回Deferred
即可以callback
被註冊的對象
from twisted.internet import defer
intermediate_deferred = None
@defer.inlineCallbacks
def example():
global intermediate_deferred
print("Started")
intermediate_deferred = defer.Deferred()
result = yield intermediate_deferred
print("Resuming for the first time with %s" % result)
intermediate_deferred = defer.Deferred()
result = yield intermediate_deferred
print("Resuming for the second time with %s" % result)
generator_deferred = example()
intermediate_deferred.callback("One")
intermediate_deferred.callback("Two")
- 什麼是真正需要返回一個Deferred對象即誰在消費呢?
- 誰用最終值調用它?
- 如果沒有返回會發生什麼?
在repl
我不明白爲什麼我需要這個返回值。我的根本問題似乎是因爲我還沒有從這些功能的消費者角度考慮問題?
所以我們需要一些web框架和想象中的代碼應該如何:
# Assume it returns 'example' function object.
function_to_call = get_routing_function(request)
d = function_to_call()
# But who takes care of calling it back? The Event Loop has to do that?
# So the Event Loop has one important job of monitoring and calling back
# such Deferred's to complete the full cycle?
d.addCallback(handle_http_response)
@defer.inlineCallbacks
def get_user_details(user_idn):
result = yield get_user_details_from_cache(user_idn)
if not result:
result = yield get_user_details_from_db(user_idn)
result = post_process_user_details(user_idn)
return result
如果有人認爲這更適合softwareengineering.stackexchange.com請讓我知道。只要它在那個話題上,我就會遷移它。 – Nishant