I have a question on the following code below (Source: https://blog.risingstack.com/node-js-at-scale-understanding-node-js-event-loop/):
'use strict'
const express = require('express')
const superagent = require('superagent')
const app = express()
app.get('/', sendWeatherOfRandomCity)
function sendWeatherOfRandomCity (request, response) {
getWeatherOfRandomCity(request, response)
sayHi()
}
const CITIES = [
'london',
'newyork',
'paris',
'budapest',
'warsaw',
'rome',
'madrid',
'moscow',
'beijing',
'capetown',
]
function getWeatherOfRandomCity (request, response) {
const city = CITIES[Math.floor(Math.random() * CITIES.length)]
superagent.get(`wttr.in/${city}`)
.end((err, res) => {
if (err) {
console.log('O snap')
return response.status(500).send('There was an error getting the weather, try looking out the window')
}
const responseText = res.text
response.send(responseText)
console.log('Got the weather')
})
console.log('Fetching the weather, please be patient)
}
function sayHi () {
console.log('Hi')
}
app.listen(3000);
I have these questions:
- When the
superagent.get(wttr.in/${city})in the getWeatherOfRandomCity method makes a web request tohttp://wttr.in/sffor example, that request will be placed on the task queue and not the main call stack correct? - If there are methods on the main call stack (i.e. the main call stack isn't empty), the end event attached to the
superagent.get(wttr.in/${city}).end(...)(that will be pushed to the task queue) will not get called until the main call stack is empty correct? In other words, on every tick of the event loop, it will take one item from the task queue? - Let's say two requests to
localhost:3000/come in one after another. The first request will push the sendWeatherOfRandomCity on the stack, the getWeatherOfRandomCity on the stack, then the web requestsuperagent.get(wttr.in/${city}).end(...)will be placed on the background queue, thenconsole.log('Fetching the weather, please be patient'), then the sendWeatherOfRandomCity will pop off the stack, and finallysayHi()will be pushed on the stack and it will print "Hi" and pop off the stack and finally, the end event attached tosuperagent.get(wttr.in/${city}).end(...)will be called from the task queue since the main call stack will be empty. Now when the second request comes, it will push all of those same things as the first request onto the main call stack but will the end handler from the first request (still in the task queue) run first or the stuff pushed onto the main call stack by the second web request will run first?