0

I'm using AJAX to get a current post data for 'Store'. And I'm using AJAX to call the data for all stores, so that I can run a distance check with turf.js to show the 3 closest nearby stores to the current post/Store. But of course, I can't access the arrays of store or stores outside of the success function due to variable scope being restricted to just the success function.

jQuery(document).ready(function( $ ) {
let cur_store_id = $('#map').attr('data-store-id');

// Get Current Store Data
$.ajax( {
    type: 'GET',
    url: '/champlainfarms/champlain-farms/wp-json/champlain/v1/store/' + cur_store_id,

} ).success( function( data ) {
     store = data;
} );

// Get all Store to calculate nearest Stores
$.ajax( {
    type: 'GET',
    url: `/champlainfarms/champlain-farms/wp-json/champlain/v1/stores/`,

} ).success( function( data ) {
    stores = data;
    console.log('Pulled All Stores');
 )};

   // Returns variable not specified as scope doesn't allow variable out
   if (stores.length > 0 ) {
        console.log ("There is more than 20 locations in Stores");
    }

)};

How do can I pass the store or stores variable outside of the AJAX .success() ? I understand AJAX is asynchronous, so how do I wait till the data is returned and then work with with it outside of the .success() ?

Andrew-ThinkUp
  • 521
  • 1
  • 7
  • 15
  • "Asynchronous" means that nothing waits. You have to do your work in the callback, or via Promises, or `async`/`await` – Pointy Apr 29 '20 at 20:42

1 Answers1

0

Why do you want to work with it outside of .success()? You said you need to wait until the data is returned, and that is exactly what .success() is for. So, you could do this:

.success( function( data ) {
    stores = data;
    console.log('Pulled All Stores');
    if (stores.length > 0 ) {
        console.log ("There is more than 20 locations in Stores");
    }
})

If you still want to be able to access the stores variable outside of .success(), you could declare it with some default empty value before the AJAX call.

Alejandro De Cicco
  • 1,216
  • 3
  • 17