Forgive me, but as an extremely new developer I fail to see how this is an exact duplicate of the questions referred to. I have no idea what ajax is, and I certainly don't understand how to adapt the proposed solutions to work in my situation.
I'm writing a very simple node app that gets a stock price from a web api, get a currency conversion value from another web api, and converts the stock price from USD to AUD. I had this working perfectly in a single file, but I've chosen to split it out in to several modules to make it easier. And now I've broken it :)
Basically I pass the ticker I wish to lookup into my GetStockPrice() function, which then perform the necessary query and returns the result.....in theory.
This is how I call my module:
var returned = GetStockPrice('AMZN');
console.log(returned);
The returned value is always 10, as it's not being updated in my GetStockPrice module.
Here is the code in my module:
var http = require('http');
var stockPrice = 10;
function GetStockPrice(ticker) {
var options = {
host: 'dev.markitondemand.com',
port: 80,
path: '/MODApis/Api/v2/Quote/json?symbol=' + ticker,
method: 'GET'
};
http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
res.setEncoding('utf8');
res.on('data', function(chunk) {
const json = JSON.parse(chunk);
stockPrice = json.LastPrice;
});
}).end();
return (stockPrice)
};
module.exports = GetStockPrice;
I understand what I'm doing wrong, the http.request is being run asynchronously, so by the time my function gets to the return statement, the async call hasn't completed, so my return value, stockPrice, is still the same as when I first initialized it. Unfortunately, I don't know how to fix it. I tried moving the return statement inside the http.request function, but that doesn't work either.
Can anyone help please?