I know that Javascript is asynchronous, but in this case I can’t see why what’s happens happen.
On line 27 below I call the function ‘GetProducer’ which is supposed to return data for a specific producer that I aim to use later on. However, when consoling it out it gets undefined, which is because the code on line 28 is executed before the data is retrieved (line 27).
How come this happens and what can I do to solve it?
1. function GetProducer(id) {
2.
3. $.ajaxSetup ({
4. url: "http://localhost/api/v1/producers/" + id,
5. type: "GET",
6. dataType: "json",
7. cache: false,
8. contentType: "application/json"
9. })
10. $.ajax({
11. success: function(data){
12. return data;
13. },
14. error: function(xmlHttpRequest, textStatus, errorThrown) {
15. console.log(xmlHttpRequest);
16. console.log(textStatus);
17. console.log(errorThrown);
18. }
19. }).done(function(data){
20. console.log(data);
21. })
22. }
23.
24. $('.modal-btn').click(function(){
25. var producerId = $(this).attr('id');
26. $('#myModalLabel').html(producerId);
27. var info = GetProducer(producerId);
28. console.log(info); // <--- undefined
29. });
A
returnstatement inside an ajax callback function is useless. The function is invoked asynchronously and you can’t expect anything to pass along your returned values to anything.If you put your
console.log()call inside the “success” callback, you’ll see a value.You’ll probably need to change your “GetProducer” function such that it too takes a callback argument:
The function would then look like this, more or less:
The callback function, therefore, would be where you place the code that deals with the “producer” information. Asynchronous programming is all about giving the API functions that handle the results when the results become available.