-1

I have made API and trying use it in my jQuery scripts. But having problems with callbacks. My JavaScript:

function findAll() {
    var users;
    $.ajax({
        url: "/user",
        type: "GET",
        dataType: "json",
        success: function (data) {
            users = data;
        }
    });
    return users;
}

Help me return received data, please. Thanks in advance.

zzheads
  • 1,368
  • 5
  • 28
  • 57
  • You can write a call back function and replace that with success function. var successCallback = function(result){console.log(result)}; success: successCallback – dharmesh Sep 09 '16 at 14:37
  • You need to place all logic that depends on the result of the request in the callback. See the question I marked as duplicate for more information – Rory McCrossan Sep 09 '16 at 14:41

1 Answers1

0

This will not work because you are returning users synchronously. The value will be undefined.

What is happening is this: - var users is declared and set to undefined by the Javascript engine

  • the AJAX callback is registered to be called when the XHR request resolves
  • var users (now = undefined) is returned
  • users is assigned the response of the XHR request. But alas! It's too late and undefined has already been returned!!

This should work:

function returnUsers(users) {
    return users;
}

var users = findAll(returnUsers);

function findAll(callback) {
 $.ajax({
    url: "/user",
    type: "GET",
    dataType: "json",
    success: callback
 });

}
nikjohn
  • 20,026
  • 14
  • 50
  • 86