What is the reason for requiring both a promise and a callback in order to store JSON data in a global variable?

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"
      }
  ]
}

Answer №1

It is highly recommended to steer clear of global variables in your code. When dealing with asynchronous calls, it's vital to ensure that all subsequent operations are carried out within the callbacks or Promise chains, passing variables as parameters whenever feasible.

A suggested approach would be:

function fetchTime(index){   
    return $.getJSON("feed.json", function(data) {  
        console.log('fetching JSON...')      
    }).then(function(data) { 
        timeData = data.programme[index],
        
        return {
            title:        timeData.title,
            startTime:    timeData.start
        }
    });
};

function processTime(timeObj) {
    ...
}

$(function(){ 
    fetchTime(0).then(processTime).fail(...); 
});

The .done callback should return the specific subset of data needed encapsulated within a Promise, and invoking processTime using

.then</code ensures automatic passage of data down the promise chain.</p>

<p>It's worth noting that error handling is also seamlessly integrated into the Promise chain - if the <code>fetchTime
function results in a rejected promise (or any exceptions are thrown), the subsequent .then call will be bypassed automatically, directing the flow to the .fail handler.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling to find your way around the header on my website? Let me give

I'm looking to display certain links prominently at the top of a page, similar to this example: "home > page1 > link1 > article 1." Can someone advise on how to achieve this using HTML, PHP, or jQuery? ...

Displaying an image within a textarea using JS and CSS

Could someone help me create a form with textareas that have small images on them? I want clicking on the image to call a function fx(). Can anyone code this for me using JavaScript/jQuery/CSS? In the image below, clicking on "GO" will call Fx() I attemp ...

Magnific Popup displaying only the initial item

As someone new to using jQuery and Magnific Popup, I am working on a grid of images. When an image is clicked, I want Magnific Popup to display a specific div containing information relevant to that particular image. <div class="grid"> <div c ...

Tips on extracting json information from Dataset by utilizing JsonConvert's SerializeObject function

Utilizing a WCF service to retrieve and send data from a database using jQuery AJAX has been challenging. Despite multiple attempts, parsing JSON data remains problematic. WCF Service: [ServiceContract] public interface IService { [OperationContract] ...

"PHP Are You Dealing with Excessive Whitespace

Currently, I am utilizing AJAX to handle the processing of my ChangePassword class, which is an extension of my DataProcessor class. For some reason, every data I receive from the AJAX response seems to have an added whitespace before it, almost like it&ap ...

Converting MySQL data to JSON format with PHP and utilizing the GROUP_CONCAT function

I've been trying to convert my home temperature table into JSON format. While I have successfully achieved this for one location using WHERE, I'm struggling to get the code right in order to group it by location, as demonstrated below. I am work ...

Encountering a 400 Bad Request error while attempting to submit a large amount of data using the POST method

Currently, I am utilizing Yahoo's YUI Ajax call for sending post requests. The page has been created using JSP, and the server being used is Tomcat 6 along with Struts 2.x. Whenever I try to send a large amount of data through the Ajax call post req ...

Leveraging AJAX for connectivity to the Twitter API

Considering incorporating Twitter functionality into my web application, I decided to conduct some tests. After researching how to call the search Twitter URL (more information available at: ) in order to retrieve tweets containing specific words or phrase ...

Using Gmail with Nodemailer is throwing an error: "Cannot add property 'mailer' on a string with value 'SMTP'."

I am facing an issue with sending data from a form to my Gmail account. Whenever I click the submit button, I encounter the same error message repeatedly. Despite researching various problems related to nodemailer, none of them match the specific problem t ...

Struggling to locate the element value in Puppeteer? Reach out for assistance with await page.waitForSelector() or await page.waitForXPath()

insert image description here[ await page.waitForSelector('.DateRangeSelectorstyles__DateInput-sc-5md5uc-2.kXffji.sc-cSHVUG.VGFsW'); await page.type('.DateRangeSelectorstyles__DateInput-sc-5md5uc-2.kXffji.sc-cSHVUG.VGFsW','01- ...

Bypassing the "Your connection is not private" error in NodeJS + Express with fetch() using Javascript

Presently, I have a setup with a NodeJS + ExpressJS client-side server that communicates with the back-end server via API calls. However, every time I make a call, I need to manually navigate to the URL of the API back-end server and click on Advanced -> ...

Combining Option Value and Name Selection Using React Hooks

Currently, I am facing a situation where I need to retrieve two different values (item.id and item.name) to set the State when selecting an item from my dropdown menu. Right now, I am only able to do this for one value (item.id). Is it possible to achieve ...

Utilizing Express.js for reverse proxying a variety of web applications and their associated assets

I am looking to enable an authenticated client in Express to access other web applications running on the server but on different ports. For instance, I have express running on http://myDomain and another application running on port 9000. My goal is to re ...

Utilizing Pushwoosh to Send Push Notifications via VB.net and JSON

I'm currently trying to send a message to a device using the Pushwoosh API through my VB.Net application with a premium account. The code seems to be working fine, but I keep receiving a 400 error code from the server. Any suggestions on what might be ...

Using $watch to monitor the existence of a variable within the AngularJS scope

I'm working on a directive that displays alerts, and I want to set up a timeout function to run whenever the 'show' variable changes. How can I achieve this? When I tried invoking the link function, all the variables - show, message, and ty ...

What is the best way to extract and format data from a database using unserialize, json decode, or implode functions in Laravel Blade?

After collecting data from a form using various methods such as Serialize, Implode, and Json_encode, the stored information looks something like this: Serialized Data +-------+----------------------------------------+------------------------------- ...

The format provided is not utilized by Datetimepicker

I've encountered an issue with the Date Time Picker provided by JQuery. Despite setting a specific format, it seems to be using its default date format which results in the following error appearing in the console: Uncaught TypeError: F.mask.replace i ...

What is the reason for the successful insertion into the database without including "http://" but encountering errors when including "http

How can I insert a site title, site address (URL), site description, and site category into my database using jQuery/JSON on the front-end? When I enter "http://" in the site address input field, the data is not inserted into the database. Here is the cod ...

React.js encountered an error: Unexpected "<" token

My journey with react.js has just begun. I am currently using Webstorm for development. I have encountered an error that I am struggling to solve. It seems like React is not being recognized even after trying to install various npm react packages. Synta ...

Modifying a single element within a class with Jquery

Is it possible to create a stack of pages on a website using JQuery? I found this image that shows what I'm trying to achieve: image. Instead of applying ID css for each page, I'd like to use JQuery. While researching similar questions, I came ac ...