0

I have the following javascript function

function getAppointments() {
    var response;
    $.getJSON('http://localhost:8000/api/appointments')
    .done(function(data) {
        response = data["appointments"];
    });
    return response;
}

when I run var a = getAppointments(); in the browser console, the function doesn't return anythin, but if I run it line by line the response gets the returned data just fine. Does anyone know how to fix this so the function works properly?

angardi
  • 367
  • 3
  • 14
  • youre returning the response before the response has come back from the server. – Craicerjack Aug 20 '16 at 21:06
  • Try placing the return inside the .done block – Nate Vaughan Aug 20 '16 at 21:08
  • @Craicerjack doesn't .done() waits until data is returned from server? – angardi Aug 20 '16 at 21:10
  • @Vld I haven't seen that post before. I'm now reading it but don't understand much. – angardi Aug 20 '16 at 21:11
  • Yes, `done()` does, but the rest of your code does not, and you're returning outside `done()`, which is before anything has returned, and this is why you can't return from an asynchronous function. – adeneo Aug 20 '16 at 21:12
  • @angardi yes `.done()` waits for the data to return but it doesnt stop the rest of your javascript from running. Javascript is sequential so it runs through your commands one by one, not waiting for the previous one to finish. `.done()` will wait for the server to return though, and then run what ever is inside it. But by this stage youve already returned the response. You dont need to wrap it all in a new function and instead could do this - `var a = $.getJSON('http://localhost:8000/api/appointments') .done(function(data) { return data["appointments"]; });` – Craicerjack Aug 20 '16 at 21:15
  • @Craicerjack Thanks, but in the code you suggested, a will get the return value from `$.getJSON()`, not the `return data["appointments"]` so I would still have to retrieve data from `reponseText` – angardi Aug 20 '16 at 21:21

0 Answers0