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.
The
return resstatement is inside AJAX call. It does not return fromgetId()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:and now in code you can use
Keep in mind that the
some other thingscode may (and will) be called before thedo something with the resultcode.Sorry about mixing CoffeeScript with JavaScript but I’m not really into CoffeeScript.