-
-
Save gr33ngr33n/50a2fa627926fa6b84778fb7df36beb2 to your computer and use it in GitHub Desktop.
Examples of sequential, concurrent and parallel requests in node.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var http = require('http') | |
| // SEQUENTIAL REQUESTS | |
| // Have to try | |
| function sequentialRequest(count){ | |
| if (count == undefined) {count = 0} | |
| count++ | |
| if (count > 5) {return} | |
| var request = { | |
| hostname: 'httpbin.org', | |
| headers: {'request-id': count}, | |
| path: '/delay/.'+ Math.floor(Math.random() * (5 - 1 + 1)) + 1 | |
| } | |
| http.get(request, (res) => { | |
| var body = '' | |
| res.on('data', function (chunk) { | |
| body += chunk | |
| }) | |
| res.on('end', function () { | |
| console.log(JSON.parse(body).headers['Request-Id']) | |
| sequentialRequest(count) | |
| }) | |
| }).end() | |
| } | |
| console.log("Running sequential requests :(") | |
| sequentialRequest() | |
| // CONCURRENT REQUESTS | |
| // Default by nature | |
| function concurrentRequests(){ | |
| for (var i = 0; i < 5; i++) { | |
| var request = { | |
| hostname: 'httpbin.org', | |
| headers: {'request-id': i}, | |
| path: '/delay/.'+ Math.floor(Math.random() * (5 - 1 + 1)) + 1 | |
| } | |
| http.get(request, (res) => { | |
| var body = '' | |
| res.on('data', function (chunk) { | |
| body += chunk | |
| }) | |
| res.on('end', function () { | |
| console.log(JSON.parse(body).headers['Request-Id']) | |
| }) | |
| }).end() | |
| } | |
| } | |
| console.log("Running concurrent requests!") | |
| concurrentRequests() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment