Hacker News new | ask | show | jobs
by k3n 4824 days ago
It's an easy way to avoid race conditions, say you have 2 ajax calls that are required to render your Main view. If either or both of the calls fail, you want to show a Default view.

One answer would be to just do them synchronously, perhaps nesting one of the api calls inside the other's callback (event-handler or otherwise). And then for the Default view, you'd need to have the code that handles the failure in 2 different places (or at least 2 tests for failure).

Another answer would be a state machine which can be grouped and chained (pipe'd) with other similar state machines, to guarantee an order of operations when you need it. With this, you create a promise which is only resolved when both of the promises for the 2 ajax calls are complete, and that promise then pipes the results to the next promise in the chain which renders your view. For the Default view, if either of the ajax calls fail then the parent promise will fail, allowing you to handle the failure in one place.

Code example:

    Deferred.when( ajax1(), ajax2() ).then( /* success */ mainView(), /* fail */ defaultView() );
1 comments

In POSIX thread programming the "state machine" that you talk about is commonly called a Condition Variable. https://computing.llnl.gov/tutorials/pthreads/#ConVarOvervie...