2017-10-10 54 views
2

假設庫有兩個功能,第一個功能需要一個URL和返回的Future一個ConnectionPython的未來組成

def create_connection(url) 
""" 
:return tornado.gen.Future containing connection 
""" 

而這需要一個連接,而不是連接的未來第二個功能,返回一個Channel的未來:

def create_channel(connection): 
""" 
:return tornado.gen.Future containing channel 
""" 

如何這兩個功能結合在一起,創建獲得一個網址頻道的未來(不使用await)?

東西的形式爲:

url = "doesn't matter" 

channel_future = create_connection(url).bind(lambda c: create_channel(c)) 

預先感謝您的關懷和響應。

回答

1

您可以創建一個協同程序(用gen.coroutine裝飾),並生成由create_connectioncreate_channel返回的期貨。

@gen.coroutine 
def bind_things_together(): 
    connection = yield create_connection(url) 
    channel = yield create_channel(connection) 

    # do something else ... 

在上面的代碼示例中,connectionchannel變量不期貨,但實際的連接和信道的目的,因爲得到的Future返回它的結果。

當您設置的連接未來的結果,龍捲風將調用bind_things_together.next()向前移動協同程序。然後在下一行,你傳遞給connectioncreate_channel。當您設置在通道未來的結果,龍捲風將再次調用.next()向前移動協同程序。在哪一點你可以做其他事情。

編輯:在再次閱讀您的問題時,您似乎想要訪問頻道的未來。在這種情況下,你不必產生create_channel()

@gen.coroutine 
def bind_things...(): 
    ... 
    channel_future = create_channel(connection) 
    # if later you want the channel object, just yield channel_future 

注:如果從另一個函數調用bind_things_together(),你將需要裝飾的是功能與gen.coroutine爲好。此外,飾以gen.coroutine任何功能也會自動返回的Future。所以,你必須使用yield關鍵字調用者得到的bind_things_together()結果。