0

I'm calling a C# api through Jquery AJAX. I am able to loop through all of the data and print each in the console; however, I am not able return the data to a variable (var x) so that it contains all objects returned from the api call.

This is my code thus far:

var uri = 'api/products';
function test(){
      // Send an AJAX request
      $.getJSON(uri)
          .done(function (data) {
            // On success, 'data' contains a list of products.

            var info = {};
            $.each(data, function (key, item) {
              // Add a list item for the product.
              console.log(item);
              info.append(item);
            });
            return info;
          });
}
var x = test();

I have tried to just simply skipping the $.each() and returning data, with no luck.

Should I be using a method other than append? Or is there a way to just simply return data? Thanks.

beckah
  • 1,543
  • 6
  • 28
  • 61

1 Answers1

0

.done() is a promise (http://api.jquery.com/promise/), which takes a callback function. The callback function is void; nothing consumes its return...and the return in your code is the return for the (anonymous) callback function, not for test(), which is why you're seeing no value come out.

This is an asynchronous pattern. That means test() is going to return immediately, not waiting for the AJAX call to complete, and there's no value yet to put into x! The AJAX response will arrive later, at some unknown time. The purpose of the callback function is to allow you to (at that time!) do whatever it is you intend to do with the value you receive. You haven't shown us what that is in this example, but you're going to need to restructure it to happen after the promise is fulfilled.

S McCrohan
  • 6,663
  • 1
  • 30
  • 39