title: asyncio running from a synchronous (standard) function
body: <p>Having read the documents and watched a number of videos, i am testing <code>asyncio</code> as an alternative to <code>threading</code>.</p>
  <p>The docs are here:
  <a href="https://docs.python.org/3/library/asyncio.html" rel="nofollow noreferrer">https://docs.python.org/3/library/asyncio.html</a></p>
  <p>I have constructed the following code with the expectation that it would produce the following.</p>
  <pre><code>before the sleep
  hello
  world
  </code></pre>
  <p>But in fact is produces this (<code>world</code> comes before <code>hello</code>):</p>
  <pre><code>before the sleep
  world
  hello
  </code></pre>
  <p>Here is the code:</p>
  <pre><code>import asyncio
  import time
  
  
  def main():
      ''' main entry point for the program '''
      # create the event loop and add to the loop
      # or run directly.
  
      asyncio.run(main_async())
      return
  
  async def main_async():
      ''' the main async function '''
      await foo()
      await bar()
      return
  
  async def foo():
      print('before the sleep')
      await asyncio.sleep(2)
      # time.sleep(0)
      print('world')
      return
  
  async def bar():
      print('hello')
      await asyncio.sleep(0)
      return
  
  
  
  if __name__=='__main__':
      ''' This is executed when run from the command line '''
      main()
  </code></pre>
  <p>The <code>main()</code> function calls the async <code>main_async()</code> function which in turn calls both the <code>foo</code> and <code>bar</code> async functions and both of those run the <code>await asyncio.sleep(x)</code> command.</p>
  <p>So my question is: why is the <code>hello</code> <code>world</code> comming in the wrong (unexpected) order given that i was expecting <code>world</code> to be printed <em>approximately 2 seconds after</em> <code>hello</code> ?</p>