I’m using an XMLHttpRequest to fetch and log symbols and prices of 2 stocks.
In this first example, I am running it synchronously, and it works fine, and manages to log information on both stocks:
let xhr = new XMLHttpRequest()
let requestUrl
let processStock = (name) => {
requestUrl =
'https://stock-price-checker-proxy--freecodecamp.repl.co/v1/stock/' + name + '/quote'
xhr.open('GET', requestUrl, false)
xhr.send()
let apiResponse = JSON.parse(xhr.responseText)
console.log(apiResponse['symbol'])
console.log(apiResponse['latestPrice'])
}
processStock('goog')
processStock('msft')
However, I know that this is a bad approach, and would like to make it asynchronous.
So, I’ve rewrote it asynchronously like this. However, only the second stock gets logged.
let xhr = new XMLHttpRequest()
let requestUrl
let processStock = (name) => {
requestUrl = 'https://stock-price-checker-proxy--freecodecamp.repl.co/v1/stock/' + name + '/quote'
xhr.open('GET', requestUrl, true)
xhr.onload = () => {
let apiResponse = JSON.parse(xhr.responseText)
console.log(apiResponse['symbol'])
console.log(apiResponse['latestPrice'])
}
xhr.send()
}
processStock('goog')
processStock('msft')
Async functions confuse me in general. As per my understanding, the two processStock executions should run independently of each other, ensuring both stocks’ data gets logged, but this does not seem to be the case.
Can someone help me understand why only the second stock gets logged?


