-2

I have the following code in a website:

              alert('step 1');
              // save token if app user: 
              if (tokenViaApp !== '' ) {
                  alert('step 2')
                  $.ajax({ 
                      type: "GET", 
                      url: "/includes/notifications/", 
                      data: {
                          t: tokenViaApp    
                      }, 
                      success: function(msg) {  
                           localStorage.token_origin = 'app';
                           alert('step 3')
                      }
                    });
              }
              alert('step 4')

If the if() passes, then i would think the alert should be in this order:

step 1
step 2
step 3
step 4

but instead I get:

step 1
step 2
step 4
step 3

Why is this the case? and how can this be changed to process correctly?

kneidels
  • 956
  • 6
  • 29
  • 55
  • 3
    It is processing correctly. `$.ajax` is asynchronous – Taplar Jun 06 '19 at 14:31
  • 2
    So, more importantly, *what is the problem?* – Taplar Jun 06 '19 at 14:32
  • You probably want to wait for the ajax request to end and then go on with step 4. Call a function from the success handler of the ajax request. – ssc-hrep3 Jun 06 '19 at 14:33
  • 1
    The title of the above duplicate doesn't appear to be a match, but it's an all-encompassing question/answer which will give you a good ground on the *asynchronous* part of *a*jax. – freedomn-m Jun 06 '19 at 14:39
  • alert 1, ok, alert 2, ok, ajax - ok, I'll fire this ajax off and get the result when it's ready/later, alert 4 - wait a bit - now I've got the ajax result back - alert 3. Does what it says on the tin. – freedomn-m Jun 06 '19 at 14:41
  • Thank you. the continued processing of the scripts on the page does not depend on the answer from the `ajax` call. but - i do not want the page to redirect before the `ajax` call has run (and there is a possible redirection further down in the script). Could this happen in theory (redirection before ajax call/complete) with the code above? – kneidels Jun 06 '19 at 14:41
  • 2
    Yes, the code after the ajax fires will continue to run - so if you redirect, it will redirect before the result is back. The server-side request itself will continue to run, it'll just never hit your success callback. You can get around this by putting your redirect in `.done()` (or the older `success:`) – freedomn-m Jun 06 '19 at 14:43

1 Answers1

1

Ajax process asynchronously which means that other synchronous functions will run while the ajax request is still processing.

If you wish the order to be correct you will need to perform step 4 inside of the call back of your ajax function.

An alternative to this could be async / await

This way you can do

const yourApiCall = () => {
    Promise.resolve(alert('step 3'))
  }
    
  const yourMainFunction = async () => {
    alert('step 1')
    alert ('step 2')
    await yourApiCall()
    alert('step 4')
  }

  yourMainFunction()

This link might help regarding the differences between async and sync

Dale
  • 580
  • 7
  • 20
  • Same syntax for jQuery? as in, use of `const`, `await Promise.resolve` etc...? – kneidels Jun 06 '19 at 14:47
  • You will probably need to use babel to use async await if you want to support old browsers https://jsfiddle.net/d19ckomt/1/ – Dale Jun 06 '19 at 15:08
  • What would the syntax be if I am passing a parameter to the function? this does not work: `function saveTokenToUser(token) = async () => {` – kneidels Jun 06 '19 at 15:22
  • Try this: https://jsfiddle.net/sdte3mwq/1/ – Dale Jun 07 '19 at 14:31