2017-01-04 29 views
1

我想了解如何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") 
  1. 什麼是真正需要返回一個Deferred對象即誰在消費呢?
  2. 誰用最終值調用它?
  3. 如果沒有返回會發生什麼?

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 
+0

如果有人認爲這更適合softwareengineering.stackexchange.com請讓我知道。只要它在那個話題上,我就會遷移它。 – Nishant

回答

0

什麼是真正需要返回一個Deferred對象即誰的 消費呢?

觸發這種內聯回調函數的代碼可以在此處註冊其後處理操作。一個例子可能是:d.addCallback(handle_http_response)

誰用最終值調用它?

內聯回調裝飾器機器是否這樣做internally。它在發電機發出StopIteration時觸發這個Deferred,即當發電機終於爲外部世界編了一些東西時。相反,yield ed值僅在generator內部使用。

如果沒有返回會發生什麼?

您只能將這些生成函數用於副作用,即不能對這些函數的輸出值執行任何操作。

相關問題