Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use await expression?

Tags:

Couldn't figure out how to use await from python 3.5-rc2

>>> async def foo(): ...     pass ...  >>> await foo()   File "<ipython-input-10-a18cb57f9337>", line 1     await foo()             ^ SyntaxError: invalid syntax  >>> c = foo() >>> await c   File "<ipython-input-12-cfb6bb0723be>", line 1     await c           ^ SyntaxError: invalid syntax  >>> import sys >>> sys.version '3.5.0rc2 (default, Aug 26 2015, 21:54:21) \n[GCC 5.2.0]' >>> del c RuntimeWarning: coroutine 'foo' was never awaited >>>  
like image 850
balki Avatar asked Aug 27 '15 02:08

balki


People also ask

How do you use await?

Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.

What is await expression?

The await expression causes async function execution to pause until a Promise is settled (that is, fulfilled or rejected), and to resume execution of the async function after fulfillment. When resumed, the value of the await expression is that of the fulfilled Promise .

Why do we use await?

await can be used on its own with JavaScript modules. Note: The purpose of async / await is to simplify the syntax necessary to consume promise-based APIs. The behavior of async / await is similar to combining generators and promises. Async functions always return a promise.


2 Answers

As per documentation, await can only be used inside a coroutine function. So the correct syntax for using it should be

async def foo():     pass  async def bar():     await foo() 
like image 159
Railslide Avatar answered Oct 21 '22 09:10

Railslide


Just like in C#, await can only be used in an async method (function).

like image 39
Melf Avatar answered Oct 21 '22 10:10

Melf