4

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?

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

If your async call returns a promise, then you can just await for it. Only when the ajax call is completed and a response is returned as a promise then only next line of codes will execute (which can include redirects also) like:

// This is a async call, can be a ajax call inside promise // we are using setTimeout with 2s delay function getCoffee() { return new Promise(resolve => { // It takes 2 seconds to make coffee setTimeout(() => resolve('Got the ☕ after 2s'), 2000); }); } // Added async to this function async function doSomething() { console.log('Making coffee first'); const coffee = await getCoffee(); // This log will only show after async call has finished console.log(coffee); // or something like redirect // window.location = "/redirecturl" } doSomething()

Comments

0

This is a basic html starting page:

<html> <head> <meta charset="UTF-8"> <title>Stack Overflow Test Redirect</title> <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> </head> <body> Content of the document...... </body> </html> 

Js part with JQuery:

$.ajax({ url: '/test/', type: 'GET', crossDomain: true, success: function() { alert("Success"); }, error: function() { alert('Failed!'); } }); 

and Vanilla JS example:

function makeRequest (method, url, done) { var xhr = new XMLHttpRequest(); xhr.open(method, url); // xhr.withCredentials = true; <--CORS ENABLED! xhr.onload = function () { done(null, xhr.response); }; xhr.onerror = function () { done(xhr.response); }; xhr.send(); } // And we'd call it as such: makeRequest('GET', '/test.com/', function (err, datums) { if (err) { throw err; } console.log(datums); }); 

Beware CORS. Hope it helps..

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.