[Tutor] What exactly does "await" do? (David)

David bouncingcats at gmail.com
Tue Feb 14 04:27:40 EST 2023


On Tue, 14 Feb 2023 at 20:03, Alphonsus Okoye <phonokoye at gmail.com> wrote:
> > From: David <bouncingcats at gmail.com> > > Date: Tue, 14 Feb 2023 00:05:32 +1100

> > > How does the await
> > > statement suspend the execution of a coroutine and still run the coroutine?
> > > I know I am missing some fundamentals here. How do I make sense of this?

> Good day Mr David and to everyone here. From what you said, the coroutine
> can be executed just like a function; the execution of the main function is
> suspended till the inner function has finished executing. What is then the
> main purpose of a coroutine?

Hi Alphonsus Okoye,

Here is a good explanation, using Python:
  https://realpython.com/lessons/what-concurrency/

The simple answer is that when a synchronous function
encounters some resource that cannot respond immediately,
the function gets stuck there. It cannot proceed. It cannot
do anything except wait for the response from the resource.

Whereas an asynchronous coroutine in that situation has a
capability to transfer execution to some other coroutine task.

This means that operations can occur in parallel. While one
coroutine might encounter a delay due to some external
resource not responding, some other coroutine can proceed.

> I assume there is a specific problem which isn't straightforward with
> normal functions. From youtube videos, the purpose of a coroutine seems to
> be to execute some IO process asynchronously, but I have also read in some
> stackoverflow page that a coroutine may still not execute asynchronously if
> not written well.

Sure.

> So how do I write asynchronous code using coroutines?
>
> More specifically, if I wished to write a program that read from a long
> text file "spam.txt", and while the process begins to waste time, do other
> stuff like call function doOtherStuff(), what would the code look like?

You can find good example Python code here:
  https://realpython.com/async-io-python/


More information about the Tutor mailing list