How await keyword works?

萝らか妹 提交于 2019-12-10 19:49:46

问题


For a given below co-routine(f),

import csv
import urllib

def f(resp):
   print('Line 1')
   yield csv.reader(resp.read().decode('utf-8'))


def h():
    url = 'http://www.nasdaq.com/screening/companies-by-industry.aspx?exchange=NYSE&render=download'    
    resp = urllib.urlopen(url)
    cr = f(resp)

cr = f(resp) assigns an iterator object to cr,

cr.next() execute Line 1 and block at yield keyword.

My understanding is, with syntax cr=f(resp) there is no event-loop(task scheduler) with threading, behind the scene


Instead of saying cr=f(resp)(above), If the same function(h) has await f(resp) as mentioned below(await keyword asks for async syntax),

async def h_async():
    url = 'http://www.nasdaq.com/screening/companies-by-industry.aspx?exchange=NYSE&render=download'    
    resp = urllib.urlopen(url)
    await f(resp)

then,

How await f(resp) different from cr=f(resp)?

How h_async() different from h()? Does await keyword introduce event-loop(task scheduler) with threading, behind the scene, as shown in this sample code


回答1:


await EXPR means event tasks scheduler can switch on something other at this step (for example, pull something that's ready from the task queue), and also indicates that EXPR is awaitable. If EXPR is a coroutine, it means it can have subsequent awaits inside, and again something else can be also executed when this coroutine is in non-blocking waiting state (like IO or network response, sleep, etc)



来源:https://stackoverflow.com/questions/54043726/how-await-keyword-works

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!