Ways to retrieve various values from an Ajax request received within a promise chain

In my geolocation app, I have been effectively utilizing promises to make asynchronous AJAX requests that return API JSON objects. Using the then() function, I have successfully chained and processed each promise's data accordingly.

However, I have encountered an issue with the last Promise in my sequence. This particular Promise does not involve calling an API; instead, it involves fetching geodata from a file. While I can easily return this data, my challenge lies in returning both the data and an additional variable from the final step of the chain. Below is the snippet of code pertaining to this problem:

// ---- Continuing from the previous promise chain ---- //

return openWeather

}).then(function(data4) {

            console.log(data4)

            // The following code snippet needs to be addressed

            $('#txtDescription').html(data4['data'][0]['weather']['description']);
            $('#txtSpeed').html(data4['data'][0]['wind_spd'] + ' mph');
            $('#txtDirection').html(data4['data'][0]['wind_dir'] + ' °');
            $('#txtTemp').html(data4['data'][0]['temp'] + ' ° celcius');

            // Data to be returned

            let iso2 = data4['data'][0]['country_code'];

            // Function to be returned

            return geoData(iso2);

        }).then(function(result) {

            // Attempting to assign two values from the returned array     

            let iso2 = result[0]
            let data5 = result[1]

            // Both console.logs yield undefined.

            console.log(iso2)
            console.log(data5);

All my AJAX calls are stored in a separate file and imported as modules for use.

function geoData(iso2) {
    return $.ajax({
        type: "GET",
        url: "countries.geo.json",
        dataType: 'json',
        success: function (data5) {
            
            // Both variables are logged to the console within this success function
            console.log(iso2)
            console.log(data5)

            // Returning both values by using an array
            
            return [iso2, data5]
        }
    });
};

While I can individually return either the data from the 'geoData()' AJAX call or the 'iso2' variable, I am unable to retrieve both simultaneously. Essentially, I require the variable for comparison in a conditional/loop that matches it with a specific country listed in the returned JSON object.

Is there a way to return two values rather than just one? Any guidance on resolving this dilemma would be greatly appreciated.

Answer №1

When making an ajax call, it is important to handle the data returned properly. Instead of trying to return multiple values directly from the ajax call, you should still return only one value but extract and use multiple values within your function. Here's an example:

function fetchUserData(userId) {
  return $.ajax({
    type: "GET",
    url: "https://jsonplaceholder.typicode.com/posts/1",
    dataType: 'json'
  }).then(response => [userId, response]);
};

fetchUserData("test").then(result => {
  console.log("User ID:", result[0]);
  console.log("User Data:", result[1]);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

Guide on how to delete the right text input based on the deletion of a specific file

Check out my new application by clicking on this link: APPLICATION Here are the steps to follow: Click on the Add Question button to add a file input to the table below: Use the file input to upload 2 images (one at a time). After each s ...

Preserve marked checkboxes upon page refresh

So I created a search engine with a filter using checkboxes in a form. The filter function is working fine when I submit the form (I'm using Flask for this). However, once the results are displayed, the checkboxes that were used as filters become unch ...

Getting a specific index from an array using the Angular ng-repeat Directive: A step-by-step guide

I am trying to retrieve a specific index in an array using the ng-repeat directive. Currently, it is displaying information for all indexes... I only want to display the information for the second index as an example... This is my main.js: app.controll ...

Jquery ripple effect does not function properly with background-attachment: fixed style

Is there a way to make the effect ripples () work with background-attachment: fixed? I'm trying to achieve this effect while keeping the background fixed in place. Any suggestions on how to make this work? background-attachment: fixed; ...

To include a request parameter in every HTTP request made with $http in AngularJS

I am looking to utilize Angular's $http service to communicate with an API. However, I need to find a way to save my authorization token within $http so that it is included in every request, whether it is a post, get, put, or delete request. I have ob ...

Incorporate external JSON data into your React application

I am fairly new to this and trying to figure out how to load an external JSON file into React and then use its data. However, I am running into some issues because the JSON hasn't loaded yet, resulting in errors like 'Cannot read property 'm ...

Arranging a collection of items by a specific attribute

const oddArray = [ { name: "1", desc: "in odd", cat: "1" }, { name: "3", desc: "in odd", cat: "2" } ]; const evenArray = [ { name: "1", desc: "in even", cat: "1"}, { name: "2", desc: "in even", cat: "1" }, { name: "4", desc: "in even", ...

What is the most effective method for sharing a form across various components in Angular 5?

I have a primary form within a service named "MainService" (the actual form is much lengthier). Here is an overview- export class MainService { this.mainForm = this.formBuilder.group({ A: ['', Validators.required], B: & ...

The closing dialogue feature is not functioning properly

Currently, I am working with primefaces version 5.0 and I have come across this particular scenario: <composite:implementation> <p:dialog id="confirmDialog#{cc.attrs.someParam}" rendered="#{cc.attrs ...

Getting the selected value from a dropdown button that utilizes the @Html.DropDownListFor tag helper in ASP.NET Core MVC

I am currently working on a dropdown button that is populated using the HTML tag helper @Html.DropDownListFor. The code snippet for this button looks like: <div class="col-sm-3" id="valueSetParent"> @Html.DropDownListFor(model ...

Tips for implementing JavaScript within PHP: Ensure the script tag is properly utilized to avoid recognition issues

Having trouble with the script tag, as the SELECT query works fine but the javascript prompt is not appearing. Instead of redirecting, all I see is a blank screen. $qry1="SELECT area, aadhar FROM user where username='$user'"; $result1 = $connect ...

Displaying a collapsible table directly centered within the table header

I am having trouble centering my table header in the web browser page. When I click the "+" button, the data is displayed beneath the table header, but I want the collapsible table to be centered directly below the header. I have tried making changes in CS ...

Is it possible to merge various jQuery setTimeout functions together?

I am currently using the following jQuery code for a specific task: setTimeout(function() { $("#ToDo1").removeClass("fa-spin fa-spinner"); $("#ToDo1").addClass("fa-check-square"); $("li:first").html("<i class='fa-li fa fa-check-square& ...

Looking to develop a dynamic password verification form control?

I am in the process of developing a material password confirmation component that can be seamlessly integrated with Angular Reactive Forms. This will allow the same component to be utilized in both Registration and Password Reset forms. If you would like ...

Is there a way to automate clicking on a hyperlink?

Is it possible to automatically play the top video in a lightbox after using AJAX to get the videos list and viewing it? ...

Angular 2 - Incorrect Pipe Argument: '' with pipe 'Async Filter'

This is the code found in component.html <select name="select1" *ngIf="optionsArr | async"> <option *ngFor="let option of optionsArr">{{option}}</option> </select> Here is the implementation in component.ts export class Compo ...

Posting a JSON array to a server using WebAPI/MVC

I'm currently facing an issue with sending two specific objects to the server. In my form, I have an input field and a text area. Send function SendServer() { $.ajax({ url: '/api/Service', type: "POST", ...

"Discover the magic of jQuery: Unveiling the hidden div with one simple CSS visibility change

I want to implement a functionality on my screen where the Previous button is hidden initially and only becomes visible when the user clicks the Next button. I have set the CSS property for the Previous button to hide it by default, but despite using an if ...

Sort by the date using a specific data attribute

My main objective is to showcase a multitude of posts on this website, sourced from a server that does not organize them by date. I, however, wish to arrange them based on their dates. Currently, the layout on my website looks something like this: < ...

The scrolling action triggered by el.scrollIntoViewIfNeeded() goes way past the top boundary

el.scrollIntoViewIfNeeded() function is used to scroll to element el if it's not within the visible browser area. Although it generally works well, I have encountered some issues when trying to use it with a fixed header. I have provided an example s ...