Create all of your promises that you know you need up-front. Build a .when
with them. Save the promise returned from the .when
. As you add new events, which require new promises, add new .when
s, using the promise from previous .when
s, plus whatever new promises you've completed.
Your application will have multiple single points of failure
, if you're using the final .when
as your "Go ahead with the app.". IE: if any one promise fails at any point, then any .when
created after that is also going to fail.
...but if that's your intent, or you've got some solid error-handling, it should do you.
I'm trying to keep this library-agnostic -- usually, I use my own implementation, which is half-way between something jQuery does, and something that Crockford did in a recent talk, but if we assume that:
functions return promise-handlers
"when" returns a promise-handler
promise-handlers have at least a .done
and .fail
-- or accept two arguments, or whatever
and whatever happens inside of a function will control whether the promise is rejected/resolved
or kept/broken
(or whatever), then you might end up with a bunch of functionality that looks like:
var doing = doSomething(), // returns promise
making = makeSomething(), // returns promise
loading = loadSomething(), // returns promise
dependencies_lvl_1 = when(doing, making, loading);
Later on, you might add a new module or widget -- maybe it saves some work:
var saving = saveSomething(), //returns promise
dependencies_lvl_2 = when(dependencies_lvl_1, saving);
Maybe after that, you need to switch pages, but you need your data to cache first
var caching = cacheData(), // returns promise
when(dependencies_lvl_2, caching)
.done(goToNextPage)
.fail(handleError);
If you look at it, you know for a fact that as long as when
returns a promise which only succeeds if all promises are kept (and when all promises are kept), and none of them broke, then dependencies_lvl_2
there, includes all dependencies from dependencies_lvl_1
, plus additional promises.
The level-3 .when
, then, has a resolution depending on every single thing which has been added to the chain.
And as long as you keep caching your promises into variables (or some sort of future-access), you can keep chaining these together, into eternity.