This question has been asked many times but I unfortunately fail to understand how to proceed.
I have a scenario in which a variable may, or may not, need to be assigned a value through an asynchronous call.
This is the code:
var continueFlag = someCondition ? true : false;
if(needToDoAjaxCallFirst){
$.post(someUrl, someData, function(response){
if(response == 'continue')
continueFlag = true;
});
}
/*
If the async call needed to be executed, then this
needs to be executed AFTER the async call is completed:
*/
if(continueFlag){
doStuff(); //do stuff here, regardless of whether the async call needed to be executed or not
}
So if the async call needs to be run, I need to wait until it has been completed before I proceed to the if(continueFlag){
part.
Normally I would simply place the if(continueFlag){
part inside the async callback function. But the problem in this case is that the code may also need to be executed even if the async call was not.
If I understand correctly, I need to use a Promise to achieve this. However, if this is indeed the case, I fail to understand how exactly.
UPDATE - one approach that I am trying to avoid:
var continueFlag = someCondition ? true : false;
if(needToDoAjaxCallFirst){
$.post(someUrl, someData, function(response){
if(response == 'continue')
continueFlag = true;
doStuff();
});
}
/*
If the async call needed to be executed, then this
needs to be executed AFTER the async call is completed:
*/
if(continueFlag){
doStuff();
}
Many people in the comments below suggest this approach as the optimal solution - and this is indeed the way I implemented it before asking the question.
However, I do not consider this a neat way to solve the problem as in this case the code to be executed in the end is the same, therefore I consider it code duplication and also not logical: It kind of creates a breakpoint where the course of the code from that point onward is split into two separate "threads"/"branches", depending on whether an async call is needed: if async call needed then go this way, else go that way
- both ways completely independent from one another, although the code run in both cases is effectively the same, hence the code duplication.
Such an approach, apart from not being logically optimal in my opinion, also adds unnecessary complexity to the code (and therefore its maintenance) as everything that needs to be done from the breakpoint onward needs to be done in minimum two places.
As one picture equals a thousand words, I am also attaching a flow chart of what I tried to describe above, in the hope that it will at least make my trail of thought clear: