zoukankan      html  css  js  c++  java
  • async/await

    asyncio提供的@asyncio.coroutine可以把一个generator标记为coroutine类型,然后在coroutine内部用yield from调用另一个coroutine实现异步操作。

    为了简化并更好地标识异步IO,从Python 3.5开始引入了新的语法asyncawait,可以让coroutine的代码更简洁易读。

    请注意,asyncawait是针对coroutine的新语法,要使用新的语法,只需要做两步简单的替换:

    1. @asyncio.coroutine替换为async
    2. yield from替换为await

    让我们对比一下上一节的代码:

    @asyncio.coroutine
    def hello():
        print("Hello world!")
        r = yield from asyncio.sleep(1)
        print("Hello again!")
    

    用新语法重新编写如下:

    async def hello():
        print("Hello world!")
        r = await asyncio.sleep(1)
        print("Hello again!")
    

    剩下的代码保持不变。

  • 相关阅读:
    Intern Day15
    Intern Day15
    Intern Day15
    Intern Day15
    Intern Day15
    Intern Day14
    Intern Day14
    纯CSS序列号
    屌丝、高富帅、文艺青年、土豪的区别
    什么是文艺
  • 原文地址:https://www.cnblogs.com/gswang/p/7390446.html
Copyright © 2011-2022 走看看