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

Concealing the rear navigation button within the material carousel

I have a material css carousel, and I am trying to hide the back button on the first slide. I attempted to use the code below from a previous post The following code snippet prevents the user from looping through the carousel indefinitely. Stop looping i ...

A Fresh Approach for Generating Unique UUIDs without Bitwise Operators

To generate UUIDs in TypeScript, I have implemented a method inspired by the solution provided on Stack Overflow. The code effectively converts JavaScript to TypeScript. generateUUID(): string { let date = new Date().getTime(); if (window.performa ...

What is the ideal way to merge Tensor objects in one graph?

I'm currently working on my web-based machine learning application, which I am building using Django and TensorFlow. Within the server-side code (views.py), I have set up various placeholders and operations that are saved globally. The HTML file "trai ...

React.js - "Encountered error: Unable to access 'map' property of undefined variable"

I've tried various methods I found through searching, but none of them seem to be working. Why is it still showing that map is undefined? import TextField from '@material-ui/core/TextField'; import Autocomplete from '@material-ui/lab/A ...

Fill a Bootstrap Table with information obtained from a JSON file source

My journey into the world of bootstrap and json files has hit a roadblock, and I need some help with the following issue: Here is a snippet of my code: <div class="container"> <h1 class="text text-success text-center ">Kontoauszug</ ...

Accessing a webpage by directly pasting the URL into the address bar is functioning properly, but is

I'm facing an issue with accessing files from a vendor's application. When I directly enter the endpoints into the browser's address bar, the file opens up without any problems. However, when I try to access them using jQuery AJAX, I receive ...

``We can showcase API data using various endpoints and then present it on a web page using

Hello from Argentina! I'm new to programming and recently started a Flask project. I've successfully displayed information from an API using one endpoint and rendered it with Flask. However, I'm now facing the challenge of displaying informa ...

The browser unexpectedly cancelled the ajax call triggered by the beforeUnload event

Seeking advice on a web application that needs to save user input data through an ajax call when they leave the site. Currently using "Fetch" in a beforeunload event listener, but encountering issues with browsers cancelling the ajax call (specifically th ...

How can I implement pagination for my HTML table using AJAX with an ASP.NET ASMX page?

I am currently working on an ASP.Net page that utilizes a Webservices.asmx webservice. I am struggling to implement pagination for my HTML table and have tried multiple approaches without success. Any guidance or assistance on how to achieve this would be ...

Using jQuery, you can easily modify the color of a TD cell by applying the css properties assigned to the div element

I am attempting to implement a jQuery script that will execute upon the loading of the document. The objective is for the script to retrieve the background color of a div located within a td cell and apply it as the background color for the respective td c ...

What are the issues with the latest API routing in Next.js?

I am encountering an error that says: SyntaxError: Unexpected token s in JSON at position 0 Here is my code: import { PrismaClient } from '@prisma/client'; import { IDPay } from 'idpay'; import { NextResponse } from 'next/server&ap ...

What is the best way to continuously make an ajax request in Angular.js and terminate it depending on the response received?

I am looking for advice on how to optimize my controller in order to run a periodic ajax call every 15 seconds instead of just once. Additionally, I am wondering how I can stop the call when needed. myApp.controller('myCntrl', function($window,$ ...

Why doesn't the z-index of child elements function properly when their fixed parents share the same z-index value?

I have utilized jsfiddle to replicate my problem. My goal is to position .top .inside above .bottom .inside. I am aware that z-index only functions within its respective position type, for example fixed and absolute do not share the same z-index level. How ...

Implementing the expand and collapse functionality to the Discovery sidebar on the DSpace 4.2 xmlui platform

I recently began using DSpace and I am attempting to implement an expand/collapse feature in the Discovery sidebar of DSpace 4.2 xmlui using the Mirage theme. After finding some helpful jquery code, I attempted to add this functionality by placing the js f ...

Guide on building a FastAPI endpoint that can handle both Form and JSON body in one request

Is it possible to design an endpoint in FastAPI that can handle both (multipart) Form data and JSON body? How can I make the endpoint recognize the type of data it is receiving? ...

Extracting information from Postgres and converting it to JSON format while dynamically updating the column names

Is there a way to selectively import specific columns from a table in json and alter their names during the process? For example: MyTable (id, column1, column2, columns3) I aim to transform them into json format as follows: MyTable: {column11, column2, ...

Tips for automatically closing all other divs when one is opened

I have multiple divs structured like this: <div id="income"> <h5 onclick="toggle_visibility('incometoggle');">INCOME</h5> <div id="incometoggle"> <h6>Income Total</h6> </div> </div> <d ...

Transmitting a custom PDF document through email with React and Node.js

Currently, I am in the process of developing an application designed to streamline the completion of a complex form. The data entered into this form will be stored on a remote database for future reference and editing purposes. Once the form is ready for s ...

Navigating the rollout of a fresh new design

When implementing a new design on a website, how can you bypass the need for users to clear their browser cache in order to see the updated changes? Is there a way to automatically refresh the cache once a new version of the website is uploaded, or are th ...

Highlight the navigation transition in the menu

Is there a more updated tutorial available for creating an underline effect that slides from one link to another when hovered over and remains at the clicked link? I have come across a tutorial on Underline transition in menu which seems to be based on th ...