In this article we will be contrasting javascript with python. At the end of the post you will be able to contrast or differentiate between asynchronous and parallel programming paradigm.
For this purpose we will look at making http requests using python and javascript.
First, lets take a look at how Python (or PHP, Java, C++) would make a http request and thus execute the code. To make a http request in python we will be using requests library.
import requests r = requests.get("http://www.techcouple.info"); print r print "Operation after the request."
Now, lets take a look at how javascript would do the same tasks. We would be using request library for nodejs.
import request = require('request'); request('http://www.techcouple.info', function(error, response, body) { console.log(response); }); console.log('Operation after the request.');
Python is a synchronous and multithreaded programming language. What that means is,
- The request used in python is a synchronous operation. We need to wait for the operation to send a result to move forward to the next statement.
- Multiple threads can be created in python to execute a piece of code (but in out example its just a single thread that we are taking into account).
Javascript on the other hand, is a single threaded and asynchronous programming language.
- Request in javascript is an asynchronous operation. Instead of waiting for the request to complete, we specify what we want to do when the request gives a response and move to the next statement.
So, in python example, “Operation after the request” statement will always print after the response from the request. Whereas, in javascript example, the “Operation after the request” statement will always get printed before the response.
To Summarize:
For simplicity sake, lets assume that each statement (for both python and javascript) takes 10ms.
Case 1: Lets assume the wait time for the request is 20ms.
For synchronous execution:
For asynchronous execution
Case 2: Wait time = 5ms
For synchronous execution:
For asynchronous execution
You must be logged in to post a comment.