2

When you call a synchronous function on the Meteor server, does it block the entire server until the callback is received?

queueTask = function(callback) { ... }
queueTaskSync = Meteor._wrapAsync(queueTask)
queueTaskSync(function(results) {
    console.log('callback returns after 10 seconds')
    Results.insert(results)
})

In other words, if the callback takes 10 seconds to return, does this mean the server cannot do anything else for 10 seconds?

Nyxynyx
  • 61,411
  • 155
  • 482
  • 830
  • I don't think that `Meteor._wrapAsync` turns async functions into synchronous ones, because I don't think that's actually possible to do. – Matt Ball Jan 16 '14 at 15:23
  • @MattBall this is exactly what `_wrapAsync` does, it uses the first and second params of the callback (err, result) typically to either throw an error or to yield using fibers – Tarang Jan 16 '14 at 15:44

1 Answers1

4

It depends where this code is. If the code is in a Meteor.methods on the server additional calls to meteor from the same client will be blocked, but other's wouldn't be blocked since they are in different fibers.

You can bypass this using this.unblock() in your method to make sure the next method calls are run in new fibers, thus making them more concurrent-like.

Tarang
  • 75,157
  • 39
  • 215
  • 276
  • If the code is in a `cursor.observe()` callback function like `added`, will it be handled differently? – Nyxynyx Jan 16 '14 at 15:53
  • I think so, where do you run the observer is it in Meteor.startup? (runs with the server - but not affiliated to a client). If you want to force it to run in a fiber you could wrap it in Fiber(function() { ... }).run() – Tarang Jan 16 '14 at 15:58
  • I run the observer outside of Meteor.startup, on `appPath/server/server.js`. It's not associated with any client. Is it better to run within Meteor.startup? I want to avoid blocking the entire server – Nyxynyx Jan 16 '14 at 16:09
  • Oh it should be ok there because it would be in a separate fiber. It shouldn't block your clients, there are certain scenarios that would depending on your code, but it doesn't look like it. It's better to put it in Meteor.startup because you would have surety meteor has loaded fully at that point. – Tarang Jan 16 '14 at 16:25
  • Thanks I'll put it within Meteor.startup. Does `Meteor._wrapAsync` puts the callback in a separate fiber? I cant seem to find documentation for `_wrapAsync` – Nyxynyx Jan 16 '14 at 16:27
  • Meteor._wrapAsync is undocumented, but it uses `bindEnvironment` which tries to use the previous fiber. (the one that `Meteor._wrapAsync` would be running in) – Tarang Jan 16 '14 at 16:31