0

I have a function that contains an ajax request and I want this function to return the result of the ajax request. Here is the function :

    function get_the_posts(cat) {

        var table = [];

        $.ajax({
            type : 'GET',
            url : get_all_the_posts + '?cat=' + cat
        }).done(function(data){
            table = data.table;
            console.log(table); // (1) There is what I need and it works
        });
        console.log(table); // (2) but there is an empty table

        return table; // empty result
   }

I know that ajax is asynchronous that means sending the request (or rather receiving the response) is taken out of the normal execution flow etc. and that's why my first console.log() is displayed after the second one. but I don't know how can I return my table filled by datas returned by the ajax request... i tryed to put the return inside the .done but it doesn't work...

Can someone help me please ? Thanks

1 Answers1

0

You should look into the concept of promises. You are using jQuery, so you could check out this: https://api.jquery.com/category/deferred-object/

Basically what you want is to return a promise that you will return the result of the ajax call (you call that in another function) and then you can work with the result.

For example:

$.when(get_the_post).then(do_something_with_it);

So instead of returning the table you return the promise and in the function do_something_with_it() you work with the result.

hering
  • 1,956
  • 4
  • 28
  • 43
Flo Ke
  • 1
  • 1