Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Control flow of an IF statement & Asynchronous function

My code is structured as follows:

IF (something) {
..stuff
..Asynchronous Function Call
}
ELSE (something) {
..stuff
..Asynchronous Function Call
}
..more stuff

Let's say the IF condition is met, the code executes 'stuff', then moves onto the Asynchronous Function Call. Will it simple do the call but get out of the IF statement and execute 'more stuff' in the mean time on the assumption of waiting for the Asynchronous Function Call to finish?

OR

Does it finish waiting for the Asynchronous Function Call to finish executing, then continue with 'more stuff' as a normal IF statement block would do.

In the prior case, any advice on how to ensure the Asynchronous Function Call finished before it exits the IF block?

** Note, I've included more stuff inside both Asynchronous Function Calls to ensure the calls are done before it moves on, but I feel this is really bad programming because if I had 50 ELIF's, I would have to copy paste that code 50 times as opposed to just putting it at the end of the IF statement.

Thank you very much for any help provided!

like image 962
ietwaroo Avatar asked Jul 10 '26 08:07

ietwaroo


1 Answers

You can approach this easily and less painfully using JavaScript Promises. Have a look to the following links:

  • http://davidwalsh.name/write-javascript-promises
  • https://www.promisejs.org/

The basic idea of JavaScript Promises is to the use of asynchronous calls that can be executed in a certain order. Like this:

$.when(GET_PRODUCTS).then(
 IF_SUCCESS DO THIS
 ELSE DO THAT
).fail(
 SHOW MESSAGE
 CLEAN EVERYTHING BECAUSE SOMETHING WRONG HAPPENED
).done(
 CLEAN EVERYTHING BECAUSE EVERYTHING WENT OKAY
)

With that, you can make code that will be more maintainable. It is not easy to grasp it at the beginning, but give it a try, will save you a lot of headaches!

like image 194
eliashdezr Avatar answered Jul 12 '26 00:07

eliashdezr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!