Async, await
-
Upload
adrian-liaw -
Category
Technology
-
view
266 -
download
1
Transcript of Async, await
ASYNC, AWAITasynchronous |eɪˈsɪŋkrənəs| (adj.) 異步的
Adrian Liaw
廖偉涵 Adrian Liawadrianliaw / adrianliaw2000http://github.com/adrianliaw
AGENDAWhat is asyncTraditional approachasyncio
PSEUDOCODEwhile not everyone is done:
person = select 1st person in the queue
if not check_homework(person):
person.fill_blanks(do go_to_queue() when done)
WHAT IS ASYNCAsynchronous I/O or non-blocking I/OSingle-threaded
Non-blocking sockets
select, epoll, kqueue
event loop"Tell me when you're done"
TRADITIONAL APPROACH
CALLBACKSfs.readFile("foo", "utf8", function (error, result) { if (!error) console.log(error); else console.log(result)});
CONS OF CALLBACKMessyHard to save stateHard to organiseBad for Python
GENERATOR
>>> def foo():... yield "foo"... yield "bar"
>>> gen = foo()
>>> gen<generator object foo>
>>> next(gen)"foo">>> next(gen)"bar"
>>> next(gen)StopIteration:
>>> def foo():... bar = yield "foo"... baz = yield bar * 10
>>> gen = foo()>>> next(gen)'foo'>>> gen.send(20)200>>> gen.throw(ValueError)ValueError:
>>> def foo():... baz = yield from bar()... print(baz)
>>> def bar():... yield 1... yield 2... return "fooooo"
PEP 3156asyncio
@asyncio.coroutinedef coro_func(): print("Sleeping...") yield from asyncio.sleep(3) print("Done")
loop = asyncio.get_event_loop()loop.run_until_complete(coro_func())
async def coro_func(): print("Sleeping...") await asyncio.sleep(3) print("Done")
loop = asyncio.get_event_loop()loop.run_until_complete(coro_func())
asyncio + aiohttp = <3Fast Scraping In Python With Asyncio
REFERENCESPEP 3156bit.ly/coroutinesDavid Beazley - Python Concurrency From the Ground Up
Q&A