Curtis Larson's Blog    Main Site    Portfolio     Archive     Feed

Meteor - How to use iron:router waitOn with an Async Server Call

How to use iron:router waitOn with an Async Server Call

There have been several posts about utilizing iron:router’s waitOn functionality for an async server call. After being disatisfied with a lot of the solutions, including my own in the aforementioned stackoverflow post, I decided to write up a simple solution that had a minimal amount of extra code in the routes file. A couple of problems that I (and many others) ran into included the waitOn function running in an infinite loop, and also waitOn executing twice.

Client Routes File

The client routes.js file is very simple, as the core functionality is contained in a different file. Basically what I am doing is returning a Util.waitOnServer call which will call the testWaitOn Meteor method on the server. You can optionally pass in arguments to Util.waitOnServer to pass data to the Meteor method. Once this call returns, we can then access the data through Util.getResponse.

Util.waitOnServer

The Util object contains all the functionality of waiting on Meteor.call. Functionality such as getResponse can be easily changed to something more eloquent, and you can also change the Meteor.call to be any async call. The arugments from Util.waitOnServer are forwarded to the Meteor method here.

Server Code

The server code is very simple, it just generates a random number and returns it. I also printed out the data argument passed to us from the client. I just wanted a way to make sure everything was being executed in the correct order.

The full source code is available on my GitHub page. If you have any questions please post them in the comments!


Curtis Larson is a LA based freelance software developer. Follow him on Twitter or send him an email if you're looking for a talented developer.