The basic pattern is if X do something asynchronously else do something synchronously. For example
if (varNotSet) {
setVarAsynchronously(function(callback) {
// process callback then...
render(page, {'var': myVar});
});
}
else
render(page, {'var': myVar});
What’s bothering me is the following
render(page, {var: myVar});
since the same code is repeated. Is there some way that I can encapsulate that logic in a single place?
If you are using jQuery, I highly recommend its build-in $.Deferred function which is available sincs version 1.5
It is made precisely to help with issues like the one you wrote.
Using jQuery, you would do this the following way:
If the deferred object’s promise was already resolved, its callback is run immediately, otherwise it runs when it is resolved. Later you can attach more callbacks to the promise with .done(), and all of them will be called immediately if the deferred object was resolved.
(You don’t have to make a promise object from the deferred object for making callbacks, it is just an optional thing that allows you to separate setting the deferred’s status from being able to add callback listeners. Otherwise you can do everything on the deferred object.