In order to expose fetched JSON data to a global variable, it is necessary to use either a promise or a callback function. However, my current code is utilizing both methods...
Currently, I am creating a promise using the .done
function in jQuery. Within this function, I aim to initialize my nowNext()
function. Shouldn't the code inside the .done
function only be executed once the promise (i.e., the JSON data) is returned?
When I call nowNext()
at this stage and log my timeObj
, it shows as an empty object. However, if I utilize timeCall()
as a callback function within .done
which then triggers the initialization of nowNext()
, my timeObj
successfully receives the JSON data.
// Defining the timeObj globally to store the retrieved JSON
var timeObj = {};
// Function fetches JSON feed, with the argument specifying the targeted object within the feed
function nowTime(i){
$.getJSON("feed.json", function(data) {
console.log('Fetching JSON...')
})
// Promise to be executed after the data has been fetched
.done(function(data) {
// Extracting timeData from the JSON based on the provided index
var timeData = data.programme[i];
// Building the timeObj with the extracted data
timeObj = {
title: timeData.title,
startTime: timeData.start
}
// Invoking timeCall to trigger the nowNext function only after timeObj is fully populated
// Directly calling nowNext here results in timeObj being empty...
timeCall();
})
.fail(function() {
console.log( "Error" );
})
};
// Fetching data for the current/now programme by invoking nowTime
$(function(){
nowTime(0)
})
// Callback ensuring that when nowNext is called, timeObj already contains the required data
function timeCall(){
nowNext();
}
function nowNext() {
console.log(timeObj)
}
A snippet of the JSON data fetched:
//////// feed.json ////////
{
"programme" : [
{
"title" : "Rick & Morty",
"startTime" : "19:00"
},
{
"title" : "News",
"startTime" : "19:30"
}
]
}