Q:

CoffeeScript:: I don't know why return function body when using ajax

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.

A:

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.

