Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to handle redirect after async call

I need, if some condition meets, make ajax call to server to update data. My function looks like following:

function doSomething() {
    if (something) {
        callSomethingAsync()
    }

    window.location = "/redirecturl"
}

My question is, is it always guaranteed that callSomethingAsync will be finished before redirect?

like image 877
SomethingElse Avatar asked Nov 06 '25 20:11

SomethingElse


1 Answers

Your code is being executed line by line. If it only consisted of synchronous operations, it would be guaranteed that the redirect happens after any code before is done processing.

However, as callSomethingAsync is an async call, you cannot expect it to be always finished before the window.location fires.

If you'd want to make sure of it, you'd include the redirect line as the last step of the callSomethingAsync function, or you'd extend the function to take a callback.

like image 91
lesssugar Avatar answered Nov 09 '25 10:11

lesssugar



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!