Skip to content
sergeych edited this page Aug 21, 2012 · 2 revisions

This class is used when you have several operations that can be run in parallel, and need to wait them all to be done before proceeding. For example, you want to load all associated records, or save changes in a few objects, or whatever else. It could be done with pleasure with Sync class like this:

class Order extends prego.Table
    markProcessed: (done) ->
        @isProcessed = true
        sync = new prego.Sync
        @save sync.doneCallback()
        @user sync.doneCallback (err, user) ->
            if user
                user.processedOrders++
                user.save sync.doneCallback()
        sync.wait (errors) ->
           return done(errors) if errors
           console.log 'Order is saved, its user processed_orders incremented and saved'  

class User extends prego.Table
    @hasMany Order

Notice that sync.doneCallback provides chaining it with your own callback. Your own callback will be called as expected. Sync keeps track of all (err) objects passed to callbacks it monitors, and store it all in array, that will be passed to sync.wait.

In the example above it is critical that a sync.doneCallback is chained in a @user association retreive, otherwise sync.wait will fire before user is retreived and saved.

Note that there could be any number of wait that all will be fired when last doneCallback() is called, e.g.

sync = new prego.Sync

...

sync.wait (errors) ->
   # do something

sync.wait (errs)
   # do somesthing else

You can use Sync callback manually:

 cb = sync.doneCallback()

 ...
 cb(null)

When attaching wait to already completed sync (when all its sync.doneCallback() were called), wait callback will be executed immediately. You can also request sync.doneCallback() for the completed sync instance, in which case it will switch to incomplete state and all following wait will be executed only again when all doneCallbacks will be called.

Note that the sync.errors is not cleared when attaching done callbacks and will continue to keep errors. You can clear it manually if need:

sync.errors = undefined
cb = sync.doneCallback()
sync.wait (err) ->
    # now err will be undefined if cb will be called with null first arg
Clone this wiki locally