协程中等待多个异步调用
代码演示:
1 import time 2 from tornado import gen 3 from tornado.httpclient import AsyncHTTPClient 4 5 6 @gen.coroutine 7 def coroutine_visit(): 8 print("*"*30) 9 http_client = AsyncHTTPClient() 10 time.sleep(10) 11 list_response = yield [http_client.fetch("https://www.baidu.com"), 12 http_client.fetch("https://www.sina.com"), 13 ] 14 print("-*-" * 20) 15 # yield 23 16 for response in list_response: 17 print(response.body) 18 print("*"*30) 19 20 21 if __name__ == '__main__': 22 print("主进程开始...") 23 coroutine_visit() 24 time.sleep(5) 25 print("主进程结束...")
执行结果:
对比之前socket里面的yield和switch,这里的执行结果就可以理解了...点击查看协程(socket)说明!
清澈的爱,只为中国