Is there a reason to use wrapAsync instead of callbacks?


#1

I’m currently using callbacks for some of my code, and I’m wondering if there’s any reason to use wrapAsync instead (performance-wise maybe?).

Thanks


#2

Are you talking about client side or server side?

Because there is no wrapAsync client side it is only applicable to the server. The reason to use it on the server is because Meteor uses a threading library called Fibers. It allows you to write sequential code on the server and not have to worry about callbacks, so you can write a function that looks like a call back, but use the return value straight away without setting up an event handler because Fibers takes care of the synchronisation for you.

However if you are using an external library, such as an NPM module, you have to use wrapAsync to make Meteor aware that this is asynchronous code, otherwise you will have issues (such as if a fiber finishes execution before a callback has returned the result can be lost).

In short, any Meteor code you write yourself should be fine and you don’t need to worry about callbacks, but if you use an external library, you need to wrap function call to that library in wrapAsync.

This of course is only true for server code, client side code is still all callback based


#3

Yes I was talking about server code.
I’m wondering though, because the behavior looks like synchronous behavior (i.e. the script is pausing until the action is finished), so I’m wondering if I’m risking potential performance issues in case I have other tasks that should be running in the background.


#4

It “looks” like synchronous, but it’s really asynchronous in the background, like ES7 async/await.
Best of both worlds !