Can someone explain why callback function after loadData(symbol) is not being called? I have this function:
function plotChart(symbol) {
alert("symbol: " + symbol);
var data = loadData(symbol, function(){
console.log("data: ",data);
});
}
I'm expecting log.console to execute after loadData completes, but nothing gets output.
In case it matters, here is the loadData function.
function loadData(symbol) {
count = 0;
quotes = [];
$.getJSON("http://localhost:8080/springboot-crud-rest/api/v1/quotes-between?symbol=IBM&startDate=2020-01-01&endDate=2020-09-30", function(data) {
data.forEach(function(item){
var quote = {};
quote.date = item.id.date.substring(0,10);
quote.open = item.open;
quote.high = item.high;
quote.low = item.low;
quote.close = item.close;
quote.volume = item.volume;
quotes.push(quote); //put quote in array
});
console.log("quotes: ",quotes);
return quotes;
});
}
Here the console.log successfully prints out the quotes correctly.
EDIT: Per @Aluan, I changed the code to look like this:
function plotChart(symbol) {
loadData(symbol).then(function(data) {
console.log("data: ", data);
});
}
function loadData(symbol) {
quotes = [];
$.getJSON("http://localhost:8080/springboot-crud-rest/api/v1/quotes-between?symbol=" +symbol +"&startDate=2020-01-01&endDate=2020-09-30")
.then(function (data) {
const quotes = data.map(function(item) {
return {
date: item.id.date.substring(0,10),
open: item.open,
high: item.high,
low : item.low,
close: item.close,
volume: item.volume
};
});
console.log("quotes: ",quotes);
return quotes;
});
}
But now I'm getting error: Uncaught TypeError: Cannot read property 'then' of undefined at plotChart (moneymachine.html:120) at HTMLTableRowElement.
Line 120 is loadData(symbol).then(function(data) {