coffeescripticed-coffeescript

How to properly return defered object in iced coffeescript


I'm trying to do async/await style of programming using coffeescript and iced coffeescript.

What I get instead if 'undefined' response.

module.exports = update: (req, res) ->
    await user = User.find({ id: 1 }).exec (err, user) ->
        throw err if err?

        console.log(err) # null
        console.log(user) # object

        defer user

    console.log user # undefined

Solution

  • Your approach will not work because the iced-coffeescript syntax for await, defer is used slightly differently. See #iced

    You have put defer into the await code block, but it is actually used a as callback for await.

    Edit: Callback function was missing.

    module.exports = update: (req, res) ->
    
      findUser = (id, cb) ->
        await user = User.find({ id: 1 }), defer err, user
        if err then return [ err, null ]
        cb err, user
    
      await findUser id, defer result
    
      console.log result.user