Pause and wait for the completion of the Ajax call within the function before assigning the object to an external variable

In my quest to leverage JavaScript asynchronously to its full potential, I am looking for a way to efficiently handle received data from API calls. My goal is to dynamically assign the data to multiple variables such as DataModel01, DataModel02, DataModel03, and so on. Given that my requirements for API data are constantly changing, I want a single place where I can specify the API endpoint and the local variable/object to store the fetched data.

Currently, the fetchDataJSON() function returns the object with the received data. However, I am faced with the challenge of making the return statement wait for the Ajax call to finish. Despite attempting various approaches like timers and callbacks, I have not been successful in synchronizing the return with the completion of the Ajax request.

After exploring similar questions on Ajax and asynchronous programming, it seems that using callbacks is the recommended approach. While I suspect that I may be missing something crucial, I am seeking guidance on how to elegantly handle this situation without resorting to cumbersome solutions like timers.

function fetchDataJSON(endpointUrl) {
    var returnObj = [];

    // Ajax call
    $.ajax({
      type: "GET",
      url: endpointUrl,
      dataType: 'json',
      async: true,
      success: updateData,
      error: handleError
    });

    function updateData(data) {
        returnObj = data;
    }

    function handleError(XHR, message, error) {
        console.log("Failed XHR");
    }

    return returnObj; // Return JSON object
}

var DataModel01 = fetchDataJSON( "http://mydata.com/endpoint/sweetjson" );
var DataModel02 = fetchDataJSON( "http://mydata.com/endpoint/somethingelse" );

EDIT: I have finally arrived at a working solution, hooray! I have marked Karman's answer as accepted since it was closest to the solution. My ultimate implementation, which drew inspiration from a colleague, is outlined below:

var DataModel01 = [];
var DataModel02 = [];

function fetchDataJSON(endpointUrl, callbackWhenDone) {
    // Ajax call
    $.ajax({
      type: "GET",
      url: endpointUrl,
      dataType: 'json',
      async: true,
      success: updateData,
      error: handleError
    });

    function updateData(data) {
        callbackWhenDone(data);
    }

    function handleError(XHR, message, error) {
        console.log("Failed XHR");
    }
}

fetchDataJSON(
    "http://mydata.com/endpoint/sweetjson",
    function(newData) { DataModel01 = newData; }
);

fetchDataJSON(
    "http://mydata.com/endpoint/somethingelse",
    function(newData) { DataModel02 = newData; }
);

Answer №1

function loadDataFromAPI(apiEndpoint, handleData) {
  function processApiResponse(response) {
    data = response;
    handleData(data);
  }

  fetchDataJSON( "http://mydata.com/endpoint/sweetjson", processApiResponse );

  function handleData(data)
  {
    // Perform operations with the received data
  }

Answer №2

To begin, ensure that you declare the variable DataModel1 at the start of your code. This will set up the necessary data structure for further operations.

Within the success method labeled as updateData, be sure to assign the retrieved data directly to the DataModel1 variable. Additionally, within this same method, establish distinctions based on specific URLs for the datamodel2 if needed.

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

Show various columns in Select2

I am currently utilizing select2 and I am interested in displaying a multicolumn table as a dropdown. In order to achieve this, the width of the drop-down container should differ (be larger) than the input itself. Is it feasible to accomplish this? Furth ...

Unable to reach a variable within the class itself

I'm facing an issue with my MobX store. In my Store class, when I try to access this.user.permits.db, I get an error stating that this.user is undefined. I am confused as to why I can't access the @observable user. src/ui/store/store.js file: ...

What regular expression should be used to meet the following requirement in JavaScript?

Criteria: Find words that begin with 'a' and end with 'b', with a digit in the middle, but are not on lines starting with '#' Given string: a1b a2b a3b #a4b a5b a6b a7b a8b a9b Expected output: a1b a2b a3b a7b a8b ...

Prevent identical values from being added repeatedly to a table while updating in real-time

Currently, I am facing an issue while running through a loop to extract values from an array. When I add a second value, it duplicates both the new and previous values in the table. For example, adding a row with value 488 works fine: <tr class="exe"& ...

Concealing an element by using parentElement.getElementsByClassName to set the display property to none

I am attempting to hide a button that generates a new element upon being clicked (to then be replaced by a delete button), but I'm struggling to set the display property to "none" when trying to target the same element using parentElement and then ret ...

TabContainer - streamline your selection process with inline tabs

I am currently working on a GUI that includes a TabContainer with two tabs, each containing a different datagrid. I initially created the tabcontainer divs and datagrids declaratively in HTML for simplicity, but I am open to changing this approach if it wo ...

Guide to Saving a List in Local Storage

I have successfully created a CRUD page where users can input text and it gets added to a list. Now, I am trying to save that list in localStorage but encountering an issue where the console log is showing an empty object. Any assistance on this matter wou ...

Mastering data binding with Vue Js is a process that requires dedication and time

I'm a Vue JS beginner and I've created a component that repeats a grid-like section. However, I've noticed that adding a dropdown in the grid is causing a significant increase in load time. As the number of records grows, the load time will ...

Tips for shortening extra text in a non-wrapping HTML table cell and adding "..." at the end

My HTML template includes text imported from a database field into a <td> tag. The length of the text can range from 3 to 200 characters, and the <td> spans 100% of the screen width. If the text surpasses the width of the screen, I want it to b ...

The efficiency of React Context API's setters is remarkably sluggish

I have a goal to implement a functionality where the background gradient of a page changes depending on whether the child's sublinks are expanded or collapsed. To achieve this, I am using the useContext hook. However, I've noticed that although e ...

What is the reason behind Google Closure Compiler appending a variable to the global namespace when the original namespace was blank?

My long script is neatly enclosed within a (function() {/.../})() to prevent any name pollution. It has been typed with complete accuracy and zero warnings. I recently discovered that Google Closure compiler initially redefines i and j in the global names ...

Implementing concurrent operations in React Native using Firebase, combining async/await with Promise.all

import fire from '../config/fire'; const db = fire.firestore(); class InitialDb extends Component { constructor(props) { super(props); this.state = { schools: '', students: '', }; } async compo ...

What is limiting me from utilizing the entire Google Calendar feed?

I currently have a public Google Calendar set up. My goal is to retrieve appointment data in JSON format from this calendar. When I utilize the following URL https://www.google.com/calendar/feeds/{calendar_id}%40group.calendar.google.com/public/basic?alt ...

Displaying a segment of information extracted from a JSON array

I'm currently tackling a project that involves using React, Redux, and TypeScript. Within the JSON file, there is a key-value pair: "data_start": "2022-09-02" Is there a way to display this date in a different format, specifical ...

Error: npx is unable to locate the module named 'webpack'

I'm currently experimenting with a customized Webpack setup. I recently came across the suggestion to use npx webpack instead of node ./node_modules/webpack/bin/webpack.js. However, I am encountering some difficulties getting it to function as expecte ...

Angular - automated pagination functionality without requiring user input

I apologize for the poorly worded title. Context In my static display angular app, I am not incorporating any user interactions and most actions are time-based. The page loads, and after a specific amount of time determined by certain elements, it reload ...

Creating a JSON file in UTF-8 format using PHP code within a WordPress plugin

I'm currently developing a WordPress plugin that requires the capability to both write and read complex data encoded as JSON, potentially containing UTF-8 encoded text. I've encountered issues when attempting to read the file, as it results in PH ...

Form input using the div element (when clicked)

I am currently working on a page that connects to a database with user information. For each user, I am creating a separate div element so that there are 6 divs total (each representing a different user). My goal is to have the ability for a user to click ...

What is the process for deleting an attribute from the RequestSpecification/FilterableRequestSpecification body?

Hey there, I've been working on a simple method that takes a String argument as a path or "pointer" to attributes in JSON, and this method is meant to remove those specified attributes. The challenge I'm facing is that while I can retrieve the ...

Dropdown menu not populating with options in AngularJS ngOptions

It's puzzling to me why the dropdown menu is not being populated by ng-options. Despite JSON data being returned from the service and successfully logged in the controller, ng-options seems to be failing at its task. <tr class="info"> <td ...