Making a synchronous call to a web API using JQuery

Understanding JQuery promises and deferred objects has been a bit of a challenge for me, so please bear with me. I should also mention that my application is built using React, Typescript, and ES6.

Let's imagine we have an array of objects:

[{ Object }, { Object}, { Object }]

I want to iterate over each object in the array, make a call to an API with a specific parameter from the object, receive the response, and then proceed to make another call to the same API for the remaining objects. Essentially, I'm looking to chain these calls together sequentially and update my application state accordingly.

Here's what I've managed to put together so far, although it's not functioning as intended:

private getData(options: any[]): void {
    let promises: any[] = [];

    options.map((option: any, key: number) => {
        let deferred: JQueryDeferred<any> = $.Deferred();
        deferred.done((response) => {
            return this.getIndividual(option)
                .done(response => {
                    console.log('done', response);
                });
        });

        promises.push(deferred);
    });

    $.when.apply($, promises)
        .then((response) => {
            console.log('response', response);
        }).fail((error) => {
            console.log("Ajax failed");
        })
        .done(() => {
            console.log('done');
        });
}

private getIndividual(option: any) {
    return apiCall(option.hashKey);
}

Answer №1

If you have multiple calls that are independent of each other and only need to take action once all the promises are completed, you can utilize Promise.all:

var xhr1 = doXhrPromise(1);
var xhr2 = doXhrPromise(2);
var xhr3 = doXhrPromise(3);
var xhr4 = doXhrPromise(4);

Promise.all([xhr1, xhr2, xhr3, xhr4]).then(() => {
  // Perform a task when all promises are resolved
});

However, if your calls need to be executed in sequence because each subsequent call relies on data from the previous one, you should chain them together like this:

doXhrPromise(1)
.then((data) => { return doXhrPromise(data.nextId); })
.then((data) => { return doXhrPromise(data.nextId); })
.then((data) => { return doXhrPromise(data.nextId); })
.then((data) => { return doXhrPromise(data.nextId); })

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

Adding schemas to the router of a Next.js 13 app is a helpful feature that can

Summary: In Next.js 13, the /app router's new changes to layout and page routing have altered how we add content to the <head>. The challenge now is how to include a schema script on each page. Next.js automatically combines <head> tags f ...

Error message displayed in console due to AJV JSON schema validation when the maximum character limit is exceeded

In this provided example: { "default": "adsds", "max": 1 } I attempted to reference the dynamically provided 'max' value and validate the number of characters entered in the 'default' field. To achieve ...

Steps to enable navigation to external pages from a ReactJS app

I am working on a simple ReactJS application: [Demo] [Source] I am trying to implement navigation within the app from external sources without refreshing the web page. This functionality should be similar to using this.props.history.push(...). /public/i ...

Locate the index of an item within an array of objects based on a matching property in the

My current situation involves having an array of objects structured like this : [ {label: "<p>Opacity | %<br/></p>", customRow: false, id: 0, items: Array(13)}, {label: "Brand_hs_id", customRow: false, id: 0, items: A ...

search for a specific value within a nested subfield of an asterisk star field in Firestore

Here is the data I have: { root: { _rEG: { fen: 'value' }, _AS: { fen: 'value' }, _BSSA: { fen: 'value' } } } I would like to query using where('root.*.fen', '==', 'value'). ...

Sluggish Performance of Material UI Table

Hey there! I've been working with Material-UI for a large data table, but I've noticed it's quite slow. Before reaching out on Github, I wanted to see if other users have any tips or workarounds to help improve performance. Here is the code ...

Convert all page links to post requests instead

Currently, I am working on a JavaScript project where my objective is to transform all links on the page into forms. This will enable the requests to be sent using the POST method rather than the GET method. The code I have implemented so far is as follow ...

Unable to choose from the dropdown menu

I'm having trouble with selecting options on a selectbox when the select option is overlapping my menu. The menu I'm using is a jQuery Plugin. When the select box overlaps the menu, the options are hidden. I tried adjusting the z-index of my div ...

Detect click outside in JavaScript for closing

While this topic has been discussed before, each issue presents its own unique challenges. Despite trying various solutions and examples for making the submenu close when clicking outside of it, I have not had any success. Is there a way to make the uslug ...

The challenge of Angular form data binding

I'm encountering an issue with binding an input box to a controller in Angular. Despite following tutorials, the model never updates when I access the property or check the scope using AngularJS Batarang. Upon form submission, $scope.licenceKey remai ...

Retrieving a string from a variable, which was imported from JS, to use as a key within

Is it possible to assign a variable as the key of an object in JavaScript? I have imported constants from a 'definitions.js' file and I need to use these constants as keys: import * as cons from '../scripts/definitions.js' export def ...

How can I create a textbox in vue.js that only allows numeric input?

methods: { acceptNumber() { var x = this.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/); this.value = !x[2] ? x[1] : '(' + x[1] + ')' + x[2] + (x[3] ? '-' + x[3] : & ...

Error: Unable to retrieve the value of a null property | ReactJS |

There are two textboxes and one button designed as material UI components. </p> <TextField id="chatidField" /> <br /> <p> <code>Enter Your Name:</code> <hr /> & ...

What is the best way to transform this Ajax query into an HTTP client request in Angular 8?

I have an ajax request that looks like this: var data = { REQUEST: 'GetFeatureInfo', SERVICE: 'WMS', VERSION: '1.1.1', LAYERS: layerName, STYLES: '', FORMAT: 'image/png', INFO ...

Issue with Socket.io Client: Consistently receiving error messages for an incorrect

Here is the server-side code: import http from 'http'; import Koa from 'koa'; import { Server } from 'socket.io'; (async () => { const app = new Koa(); var server = http.createServer(app.callback()); var io = new Se ...

An example of using quotes within quotes is an HTML tag embedded within JavaScript code

Currently, I'm working on a JavaScript code where clicking assigns the function getImage the source of an image to be displayed later on the page. The issue I'm facing revolves around dealing with quotation marks. <img src="bill.jpg" class=" ...

When attempting to access endpoints from other computers, the connection to Express.js is being refused

I have set up an Express server and React for the frontend. The express server is running on port 5000 and React on port 3000. Additionally, I am using JWT tokens for authentication. When I login to the app from the computer it is running on, everything w ...

Having trouble getting the reset select function to work

I'm in the process of developing a website where I'm facing an issue with resetting my form that is constructed using jQuery Uniform. Despite my efforts, I am unable to successfully reset it. Below is the header code snippet: $j(function() { ...

I am encountering an issue regarding the 'endpoint' property within my environment.ts file while working on an Angular 17 project

My goal is to incorporate the property endpoint from my environment.ts file into my service: export const environment = { production: false, endpoint: 'http://localhost:3000/api/cabin/' }; This snippet showcases my service: import {Injectabl ...

using laravel to make ajax requests with dynamic parameters

I'm facing an issue with an ajax call. The specific url I am trying to retrieve data from is: localhost/public/getCode?course_id=1&task_id=1 This is the ajax call I have set up: function getCode() { $.ajax({ ...