title: What is the Python equivalent of a Promise in JavaScript?
body: <p>I am trying to understand what would be the best code structure or a design pattern that would do the following:</p>
  <p>Have a function named <code>get_data</code> that would start up a socket connection and will start waiting for a specific socket event that would return some data. Once it gets the data, only then the <code>get_data</code> function should be returned.</p>
  <p>So in JS it would be very simple like this:</p>
  <p><em>(Keep in mind that this code snippet is an example, it's not meant to be a working code)</em></p>
  <pre class="lang-js prettyprint-override"><code>const getData = async ()=&gt;{
    return new Promise((resolve, reject)=&gt;{
      const socket = socket()
      socket.on(&quot;message&quot;, (data)=&gt;{
        resolve(data)
      })
      socket.connect(&quot;localhost&quot;)
    });
  }
  
  const parseData = async () =&gt; {
    const data = await getData()
    // do something with the data
  }
  </code></pre>
  <p>With python however, I have absolutely no idea how to achieve the same result.</p>
  <p>How would I translate it to python? What strategy would be used here?</p>
  <p>The only way I could think of right now is like this:</p>
  <pre class="lang-py prettyprint-override"><code>def get_data():
    socket = socket()
    my_data = None
  
    @socket.event
    def message(data):
      nonlocal my_data
      my_data = data
  
    socket.connect(&quot;localhost&quot;)
    
    while not my_data
      time.sleep(0.3)
    
    socket.disconnect()
    return my_data
  
  def parse_data():
    data = get_data()
    # do something with the data
  </code></pre>