Making async for loops in Python

后端 未结 3 917
耶瑟儿~
耶瑟儿~ 2021-01-02 05:33

The following code outputs as follows:

1 sec delay, print \"1\", 
1 sec delay, print \"2\", 
1 sec delay, print \"1\", 
1 sec delay, print \"2\"
3条回答
  •  失恋的感觉
    2021-01-02 06:10

    To run the two functions simultaneously you can use gather. However, the results will be provided to you in the order you provide them. So for example if you do

    results = await asyncio.gather(first(), second())
    

    Then you will get [the result of first(), the result of second()] back. If you want to do something whenever each one returns then you should use Tasks explicitly and add callbacks.

提交回复
热议问题