Reputation: 792
I'm new to Coffeescript, and I have a question about Ajax.
jQuery ->
api =
getId: ->
res = []
$.ajax
dataType: "jsonp"
url: "http://localhost:3004/videos.json"
success: (data) =>
if data
data.forEach (elem) =>
embed_id = elem.video_id
res.push(embed_id)
console.log res
return res
I try this code, then
console.log res
the output is
["id1","id2","id3",...] .
So I expect api.getId()
to return ["id1","id2","id3",...]
Instead, I see
Object
-> abort
function(a) {...}
...
-> status: 200
...
-> success: function (){...}
in my debug window.
I want to return the value of the response.
Upvotes: 0
Views: 798
Reputation: 56477
The return res
statement is inside AJAX call. It does not return from getId()
function, but inner AJAX callback. You cannot do this like this. AJAX calls are asynchronous, while you want them do be synchronous. I would advice you to do something like this:
jQuery ->
api =
getId: (callback) ->
res = []
$.ajax
dataType: "jsonp"
url: "http://localhost:3004/videos.json"
success: (data) =>
if data
data.forEach (elem) =>
embed_id = elem.video_id
res.push(embed_id)
callback(res)
else
callback(null)
error: =>
callback(null)
and now in code you can use
api.getId(function(res) {
// do something with the result.
});
// some other things
Keep in mind that the some other things
code may (and will) be called before the do something with the result
code.
Sorry about mixing CoffeeScript with JavaScript but I'm not really into CoffeeScript.
Upvotes: 0
Reputation: 262534
This is not really a Coffeescript problem, this is just how asynchronous requests work. You cannot immediately return the result from the XHR call, you have to define a callback that get receive the result (or the error) once that call completes.
Take a look at what your code compiles to (as Javascript).
getId: ->
## .. snip ..
$.ajax ## .. snip ..
You have a function getId
, which returns the return value of $.ajax
, which is (according to the jQuery spec) an XHR object, not the result of the success callback. You could use it to check on the progress, abort the request, set more options and so on.
success: (data) =>
## .. snip ..
return res
There is no point in returning anything from an XHR success callback. You need to work with the data right here, for example putting it into the DOM somewhere, or calling another function that does something useful with it.
Upvotes: 1