In my sequence of functions, the first function is asynchronous and returns a promise. This first function also calls other async functions. The second function should only be called when all the nested functions have completed. Therefore, I need to resolve the deferred object at multiple points within the chain (in this example, within three nested functions).
var deferred = Q.defer();
first().then(second);
function first() {
nestedAssyncFunction_1();
nestedAssyncFunction_2();
nestedAssyncFunction_3();
return deferred.promise;
}
function second() {
// perform some actions
}
My primary question here is: how can I resolve a deferred object in multiple steps?
I have discovered that by using the `notify` method at various points and resolving the main deferred object inside its handler seems to work. Here is an example:
var deferred = Q.defer();
deferred.progressCounter = 0;
first().then(second, undefined, notifyHandler);
function notifyHandler() {
deferred.progressCounter++;
if (deferred.progressCounter === 3) {
deferred.resolve();
}
}
function nestedAssyncFunction_1() {
// perform some actions
deferred.notify();
}
However, this brings me to another question: what is the most effective way to add custom properties to a deferred object? It appears to be discouraged based on the example above.
Thank you.