CoffeeScript ::我不知道为什么在使用ajax时返回函数体

时间:2012-03-12 08:49:16

标签: javascript ajax coffeescript

我是Coffeescript的新手,我对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

我尝试使用此代码,然后

console.log res 

输出

["id1","id2","id3",...] . 

所以我希望api.getId()返回["id1","id2","id3",...] 相反,我看到了

Object 
  -> abort
    function(a) {...}
  ...
  -> status: 200
  ...
  -> success: function (){...}

在我的调试窗口中。

我想返回响应的值。

2 个答案:

答案 0 :(得分:1)

这实际上不是Coffeescript问题,这只是异步请求的工作方式。您不能立即从XHR调用返回结果,您必须定义一个回调,一旦该调用完成,就会收到结果(或错误)。

看看你的代码编译成什么(如Javascript)。

getId: ->
   ## .. snip ..
   $.ajax ## .. snip ..

你有一个函数getId,它返回$.ajax的返回值,它是(根据jQuery规范)一个XHR对象,而不是成功回调的结果。您可以使用它来检查进度,中止请求,设置更多选项等等。

success: (data) =>
      ## .. snip ..
      return res

从XHR成功回调中返回任何内容都没有意义。你需要在这里使用数据,例如将它放在某个地方的DOM中,或者调用另一个对它有用的函数。

答案 1 :(得分:0)

return res语句在AJAX调用中。 getId()函数返回,但内部AJAX回调。你不能这样做。 AJAX调用是异步的,而您希望它们是同步的。我建议你做这样的事情:

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)

现在在代码中你可以使用

api.getId(function(res) {
  // do something with the result.
});
// some other things

请注意,在some other things代码之前可能(并将会)调用do something with the result代码。

很抱歉将CoffeeScript与JavaScript混合在一起,但我并不是真的喜欢CoffeeScript。

相关问题