Created
November 26, 2021 23:21
-
-
Save alanwsmith/0ff90dc5a5147f631c9247b9c7bdf809 to your computer and use it in GitHub Desktop.
Trying to figure out why https calls happen together at the end instead of interspersed
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
// The code below will output: | |
// | |
// Getting: https://www.example.com/ | |
// Getting: https://www.example.org/ | |
// Getting: https://www.example.net/ | |
// 200 | |
// 200 | |
// 200 | |
// | |
// Given that there's a 5 second delay between https | |
// calls, I would expect the status codes to generally | |
// come directly after the output for the URL. | |
// | |
// For example: | |
// | |
// Getting: https://www.example.com/ | |
// 200 | |
// Getting: https://www.example.org/ | |
// 200 | |
// Getting: https://www.example.net/ | |
// 200 | |
// | |
// It seems like the https.get() calls aren't firing | |
// or, at least, not triggering their callback, until | |
// the urls.forEach() loop has completed. I don't | |
// understand that. | |
const https = require('https') | |
const urls = [ | |
'https://www.example.com/', | |
'https://www.example.org/', | |
'https://www.example.net/', | |
] | |
function sleep(milliseconds) { | |
const date = Date.now() | |
let currentDate = null | |
do { | |
currentDate = Date.now() | |
} while (currentDate - date < milliseconds) | |
} | |
function processResponse(response) { | |
console.log(response.statusCode) | |
} | |
urls.forEach((url) => { | |
console.log(`Getting: ${url}`) | |
https.get(url, (response) => { | |
processResponse(response) | |
}) | |
sleep(5000) | |
}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment