Okay, so let’s see a slightly bigger example that we can actually run. The following code is a pretty simple asynchronous program that fetches JSON from Reddit, parses the JSON, and prints out the top posts of the day from /r/python, /r/programming, and /r/compsci.
The promise of asynchronous PHP
python simple-requests
The goal of this library is to allow you to get the performance benefit of asynchronous requests, without needing to use any asynchronous coding paradigms. It is built on gevent and requests.
Usage
from simple_requests import Requests # Creates a session and thread pool requests = Requests() # Sends one simple request; the response is returned synchronously. login_response = requests.one('http://cat-videos.net/login?user=fanatic&password=c4tl0v3r') # Cookies are maintained in this instance of Requests, so subsequent requests # will still be logged-in. profile_urls = [ 'http://cat-videos.net/profile/mookie', 'http://cat-videos.net/profile/kenneth', 'http://cat-videos.net/profile/itchy' ] # Asynchronously send all the requests for profile pages for profile_response in requests.swarm(profile_urls): # Asynchronously send requests for each link found on the profile pages # These requests take precedence over those in the outer loop to minimize overall waiting # Order doesn't matter this time either, so turn that off for a slight performance gain for friends_response in requests.swarm(profile_response.links, maintainOrder = False): # Do something intelligent with the responses, like using # regex to parse the HTML (see http://stackoverflow.com/a/1732454 friends_response.html
How to return the response from an asynchronous call?
I tried to return the value from the success callback as well as assigning the response to a local variable inside the function and return that one, but none of those ways actually return the response.
Synchronous
Imagine you make a phone call to a friend and ask him to look something up for you. Although it might take a while, you wait on the phone and stare into space, until your friend gives you the answer you needed.
Asynchronous
You call your friend again for the same reason. But this time you tell him that you are in a hurry and he should call you back on your mobile phone. You hang up, leave the house and do whatever you planned to do. Once your friend calls you back, you are dealing with the information he gave to you.
Solution(s)
Embrace the asynchronous nature of JavaScript! While certain asynchronous operations provide synchronous counterparts (so does “Ajax”), it’s generally discouraged to use them, especially in a browser context.