I got an application which needs to execute some booting/startup like:
- ajax
- dynamic requirejs
- routing, set up something else
before able to run.
I now got difficulties organizing these tasks in a solid way together. Especially the async behavior is giving me headache. Currently I am using events to share fetched results and watch the state of the application. Unfortunately this resulted in enological, inconvenient crap. Then I tried using some promises libraries like q, jquery.defered but they don't really match my problem.
This is a simplified version of the code:
// this could be an ajax call fetching some user data
var fetchUser = function() {
var user = {};
// lets emulate the ajax call with setTimeout
setTimeout(function() {
// set some values
user.username = 'bodo';
user.password = 'helloKitty';
// return the user object we "fetched"
return user;
}, 300);
};
// this could fetch some config or some requirejs modules
var fetchConfig = function() {
var config = {};
// we emulate this too...
setTimeout(function() {
return config;
}, 200);
};
// this could be anything else like setting up some objects
var justSetUpSomething = function() {
var someObj = {};
someObj.router = 'this could be a router object for example';
someObj.logger = 'or a logger';
return someObj;
};
// in the final step everything should be merged together
// and be passed as event argument
var finalStep = function(user, config, someObj) {
var mainObj = {};
mainObj.user = user;
mainObj.config = config;
mainObj.someObj = someObj;
// trigger some event system
trigger('everything:ready', mainObj);
};
Also viewable at: http://jsfiddle.net/uzJrs/3/
I hope this describes my problem:
There are three totally different, async tasks. When they all a ready their results have to get merged and somehow passed to another object.
Events make this workable but far a way from understandable and promises also don't really make me happy. Isn't there another helpful design pattern?