I am struggling with how to handle this special case. I know I could solve this with chained callbacks, but it seems like almost a poster child for promises:
I have a parent method that needs to execute three async things in order (specifically getting confirmation from a user). We'll call them func1 func2 and func3. Now I can have each of these return a promise and chain those and that is all working great. The issue I run into is:
func1 needs to set a state, wait on the rest of the chain to run, and then unset that state.
demonstration pseudocode:
function wrapper(){
func1()
.then(func2())
.then(func3());
}
function func1(){
return new Promise(function(resolve, reject){
//do some async stuff that itself returns a promise :)
async1().then(function(value){
//set some global states based on the value for the duration of this chain
resolve(); //Note NOT returning value as it's irrelevant to the other functions
//!!! clean up the global states regardless of future failure or success, but after one of those.
}, reject); //if async1 rejects, just pass that right up.
});
}
function func2(){
//do some logic here to decide which asyn function to call
if (/*evaluates to */true){
return async2(); //another async function that returns a promise, yay!
} else {
return async2_1(); //also returns a promise.
}
}
function func3(){
//do some dom updates to let the user know what's going on
return Promise.resolve(async3()).then(function(){
//update the dom to let them know that everything went well.
});//returns this promise chain as a promise which the other chain will use.
}
The part I'm struggling with is the line in func1 after resolve(); Note that as said there async1 which I'm calling in func1 does return a promise so I am already working with promises a lot here. I need the cleanup to happen AFTER the promise returned from func3 resolves.
Ideally this would all be contained in func1 in some way, but I'm also ok with a semi-global variable (this entire block will be wrapped in a larger function).