1

I have the following asynchronous Meteor method. However, createItem() is not waiting for Items.insert's callback to fire before returning.

# Relevant pieces shown here (coffeescript, more parens than usual for js folks :-)

Meteor.methods(
  createItem : (doc, callback)->
    asyncInsert = Meteor.wrapAsync( Items.insert, Items )
    results = asyncInsert( doc, (err, result) ->
      return callback(err, result)
    )
    return results
)

asyncMeteorCall = Meteor.wrapAsync( Meteor.call )
status = asyncMeteorCall( "createItem", {name:"some item"}, (err, result)->
  if err?
    return "Error adding Item"
  else
    return "Successfully added Item"
)

console.log( status ) # prints : undefined 

I did find this possibly related issue, but not sure if it's relevant, I'm actually doing all of the above on the server.

Community
  • 1
  • 1
tolmark
  • 1,746
  • 1
  • 13
  • 19

1 Answers1

2

All of the Mongo.Collection methods that accept a callback are automatically run synchronously when called on the server (as long as the callback is omitted), so there's no need to wrap them. You should just be able to call Items.insert() directly.

From the Meteor docs:

"On the server, if you don't provide a callback, then insert blocks until the database acknowledges the write, or throws an exception if something went wrong."

kahmali
  • 557
  • 6
  • 10
  • Got it, I had read that, but didn't appreciate that adding a callback stopped the blocking effect. Thanks! – tolmark Feb 25 '15 at 00:26