简体   繁体   中英

How to return multiple values from an Ajax request that is called in a promise chain

I have been using promises to call asynchronous AJAX request functions that return API JSON objects for my geolocation app. I have been successful at this using the then() function to chain and return each promise's data and use it accordingly.

The last Promise I want to use does not call an API it is a file which contains geodata. I have no problem returning this data but what I need to do is return the data and an additional variable from the last then() chain. Here is the last section of the code and the AJAX function.

 // ---- Following previous promise chain ---- // return openWeather }).then(function(data4) { console.log(data4) // Disregard this code $('#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'); // I need to return this variable let iso2 = data4['data'][0]['country_code']; // I also need to return this function return geoData(iso2); }).then(function(result) { // I am trying to assigin two values from a returned array let iso2 = result[0] let data5 = result[1] // Both console.logs read as undefined. console.log(iso2) console.log(data5);

I have my AJAX calls in another file and I am importing them as modules.

 function geoData(iso2) { return $.ajax({ type: "GET", url: "countries.geo.json", dataType: 'json', success: function (data5) { // both the variables log to the console here so I know they are being sent to the success function console.log(iso2) console.log (data5) // The only way I can think to return both values is to return an array. return [ iso2, data5 ] } }); };

I can return either the data from the 'geoData()' AJAX call or the 'iso2' variable, but not both. I basically need the variable to use in a conditional/loop that will compair with the returned JSON object and match it with a specific country.

Is it possible to return two values instead of just one? I would really appreciate the help.

That is not how you return data from the ajax call. Instead of returning 2 values from an ajax call, you still return one value from the call, but 2 values from your function, like so:

 function geoData(iso2) { return $.ajax({ type: "GET", url: "https://jsonplaceholder.typicode.com/posts/1", dataType: 'json' }).then(data => [iso2, data]); }; geoData("test").then(result => { console.log("result[0]", result[0]); console.log("result[1]", result[1]); })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM