没有方法错误(访问异步函数内的方法)

时间:2013-11-15 13:56:48

标签: javascript node.js coffeescript

我正在开发一个Zappa应用程序,并且遇到了我认为我的JavaScript知识瓶颈。问题是我无法找到一种方法来访问异步函数中的函数。

当我在CoffeeScript中时,我记得使用that = @( that = this )类型的作品。我还尝试了=>而不是->,但没有取得任何成功。

这是错误消息:TypeError: Object #<Object> has no method 'convertUploadedImage'

我怎样才能克服这个?

问题出在:

        .on "end", () ->
          file.end()
          console.log "log inside"
          console.log that.constructor.name
          that.convertUploadedImage file

提前感谢。

整个代码(或者至少我认为重要的代码):

{@app} = require('./node_modules/zappajs') ->
  @post "/collage/upload", (req, res) ->
    # We might be uploading two types of files
    #   1. web form 
    #   2. as a link
    #

    # Check for the upload URL to exist
    url = req.body.upload_url # if req.body.upload_url
    console.log "URL is - #{url}"
    # URL is present - Retrieve the proper file
    if url 
      # setting up for download
      http     = require 'http'
      fileName = url.split('/').pop()
      file     = fs.createWriteStream __dirname + "/public/images/uploads/temp/#{fileName}"

      that = @
      console.log that.constructor.name
      # download the file
      request = http.get "#{url}", ( res ) ->
        res.on "data", (data) ->
          file.write data
        .on "end", () ->
          file.end()
          console.log "log inside"
          console.log that.constructor.name
          that.convertUploadedImage file

    # URL is not present
    else
      file = req.files.files[0]
      @convertUploadedImage file

  convertUploadedImage: ( file, deleteOriginal = false ) ->    
    # Checking file type
    console.log file.type

1 个答案:

答案 0 :(得分:0)

查看文档的这一部分(http://coffeescript.org/#fat-arrow),胖箭应该有效:

  request = http.get "#{url}", ( res ) =>
    res.on "data", (data) ->
      file.write data
    .on "end", () =>
      file.end()
      console.log "log inside"
      console.log that.constructor.name
      @convertUploadedImage file