Why don't values return when using a different js file for my functions?

Hi all

To make my code cleaner I decided to make a new js file for my functions, called ‘Jfuncs.js’

As you can see in the image below, when I use the ‘fetch_price()’ function found in ‘Jfuncs.js’, the return value of the variable ‘price’ is ‘undefined’.

But, as shown in the image below, if we ‘console.log()’ the value of ‘price’ within the ‘fetch_price()’ function in the ‘Jfuncs.js’ file, the value of price is in fact not undefined.

How do I fix this so that ‘log1’ shows the price?

Thanks for your time

Jaime

Your project link(s) https://replit.com/@jaimeggb/boilerplate-project-stockchecker-1#controllers/Jfuncs.js

solution: https://replit.com/@jaimeggb/boilerplate-project-stockchecker

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36

Challenge: Stock Price Checker

Link to the challenge:

I also notice that the logs are in opposite order that I would have expected. I would expect some king of Promise or async/await for call to fetch_price. But ultimately, the return price; is returning in the callback function stored in xhr.onload, not returning from fetch_price, right? Try returning some test value from fetch_price.

1 Like

Hi @kevinSmith , thanks for your reply!

In the end what worked (although, according to the documentation, it does not seem like an ideal solution) was changing this line:

from xhr.open('GET', requestURL, true); ----to----> xhr.open('GET', requestURL, false);

And then placing return price AFTER xhr.send() (instead of within xhr.onload())

Here is the documentation for this change: