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

Creating multiple nested ng-repeats in an AngularJS table

Managing a large amount of data on users' availability by hour for multiple days can be challenging. The data is structured as follows: availData = { "date1":arrayOfUsers, "date2":arrayOfUsers, ... } arrayOfUsers= [ userArray, userArray, ... ] user ...

retrieving a key from a JSON object

Currently, I am developing a Blazor application where I have encountered an issue with extracting a value from a Json string. The Json data that I am working with looks like this: {"a1":"a1234","e1":"e1234} I specificall ...

The self-made Ajax call for deleting an action in yii2 is not functioning as expected

Trying to implement a custom Ajax request in my Yii2 application for performing a delete action. The code snippet for the action column button: 'delete' => function ($url, $model) { return '<span class="glyphicon glyphicon-trash ...

Error message occurs when trying to use the `memo` method on a `nil` object class while using the `best

I have successfully added a basic memo feature to my app and enabled in-place editing using the best_in_place gem. However, I am encountering an issue when trying to create new memos with in-place editing. The code snippet I have been using is causing an ...

Best way to eliminate empty options from dropdown and ensure that required validation is functioning in AngularJS?

My dropdown is populated with owners from the owners data, but it includes an extra blank option. I need to eliminate this blank option. However, when I make the necessary changes to remove it, the required validator stops working properly. <md-input-c ...

What are some strategies for stopping a form from redirecting me while utilizing ReactJS and ExpressJS?

Recently, I created a form that redirects to the route /repair upon submission with an action of /repair. However, I would prefer to keep it as a Single Page Application (SPA) where after submitting the form, the fields are cleared, and a simple message l ...

Ways to hide notifications by setting a timer while keeping the delete option visible

Presently, this is the code I am working with using Javascript and Vue.js. I have an array called Messages.length that contains messages. When the x button is clicked, it triggers the "clearMessages(item)" function on the server side. However, I also aim ...

Utilizing null values within the map function in React JS

I am currently developing an application using React JS. The app displays a list of users along with the status of books (available, taken, or requested) for each user. However, I'm encountering an issue where even after filtering out the books based ...

Clicking two times changes the background

I am facing an issue with three boxes on my website. Each box is associated with a corresponding div. When I click on any box, the div displays and the background color turns red. However, when I click on the same box again, the div disappears but the back ...

Using brush strokes to create a unique design on the canvas page

Currently, I am working on implementing a brush-like effect on a web page. The task involves providing multiple patterns/textures in the background and allowing users to drag their mouse to create the pattern effect on the page. If you want to see the st ...

A simple method to determine the length of a response list in Python when using the requests module

When I'm using the request library to parse data, it returns a list of JSON data. However, when I try to find the length of the response list, I encounter an error that states TypeError: object of type 'Response' has no len(). Here is the co ...

Sending a post request to a Spring controller with ajax: Step-by-step guide

I am having trouble sending a post request to the spring controller using ajax. It seems that something is not working correctly. If anyone can help me figure out what I did wrong, I would greatly appreciate it. $("#myprofile").on('submit&ap ...

"Using angularjs's $location.search method results in an empty object being

I am trying to retrieve my URL querystring in AngularJS using the $location service, similar to this example. My URL looks like this - http://someDomain.com/create/index.jsp?queryToken=123abc However, in my directive: vm.queryParam = $location.search(); ...

Issues with object changes not reflecting in Vue.js 2.0 component rendering

I am facing an issue where my object is not updating immediately after a click event. It appears that a manual refresh or clicking on another element is necessary for the changes to take effect. How can I ensure that the object updates without the need for ...

Find the name of the region in the user's query

I've implemented the weather-js npm module (weather-js) to retrieve weather information for a specific region. While everything is functioning correctly, I'm looking to customize it based on user input. The module currently only accepts region ...

Display a list of errors from an array in JavaScript or jQuery, and output them into a designated <

I need assistance with displaying a list of error messages in a specific div. Within my code, I have a #error-list div and an array called errors that contains various error messages: var errors = ["First name is blank", "Last name is blank", "Company na ...

Maintaining TextBox State in ASP.Net Through Postbacks

Can anyone help me figure out how to maintain the control state that has been modified in Javascript? I am working with two TextBoxes, one DropDownList, and a button (all Runat=Server) in C# ASP.net 2010 Express. The first textbox accepts any user in ...

Save this as a data structure

ANSWER: Each key ending with :private contains a __get() and toJSON() method, which is essential for retrieving data from them since _propMap is private. I am utilizing PayPal's PHP API to process payments from PayPal. After completing a paym ...

Testing for a panic in Golang: A comprehensive guide

func good(json) string { \\do something err = json.Unmarshal(body, &list) if err != nil { panic(fmt.Sprintf("Unable to parse json %s",err)) } } func Testgood_PanicStatement(t *testing.T) { Convey("And Invalid Json return error", ...

Problem with translating a variable into a selector in JQuery

When attempting to make my Jquery code more flexible, I decided to extract the selector and access it through a variable. However, despite creating variables for both selectors, neither of them seem to be functioning properly. I am confident that the issue ...