I have a code like this below (partial code). After the 'step 4' part the code continues and might direct to a new page (unrelated to the result of the saveTokenToUser function. BUT - i need to be sure that the saveTokenToUser and the ajax call in it have completed before the redirect happens.
Currently, I get the following result, despite having the async and await in the function call. I am guessing I just have a wrong syntax?
Step 1, Step 2, Step 4, Step 3
Code
alert('Step 1');
             // save token if app user: 
              if (tokenViaApp !== '' ) {
                  alert('Step 2')
                  var result  =  saveTokenToUser(tokenViaApp);
             }
alert('Step 4')
 async function saveTokenToUser(token) {
        await $.ajax({ 
          type: "GET", 
         // async: false,  // deprecated in jQuery 1.8
          url: "/includes/notifications/", 
          data: {
              t: token
          }, 
          success: function(msg) {  
               localStorage.token_origin = 'app';
               alert('Step 3')
          }
        });
 }
UPDATE:
Following Answer by T.J. Crowder, this is now my code.
JS FIDDLE LINK: https://jsfiddle.net/kneidels/8nsyegz3/
console.log('Step 1')
(tokenViaApp === '' ? Promise.resolve() : saveTokenToUser(tokenViaApp))
    .then(() => {
        // Do the redirect
        console.log('Step 2');
    })
    .catch(error => {
        // Handle/report error
    });
    console.log('Step 4');
async function saveTokenToUser(token) {
        await $.ajax({ 
          type: "GET", 
         // async: false,
          url: "/includes/notifications/", 
          data: {
              t: token
          }, 
          success: function(msg) {  
               localStorage.token_origin = 'app';
               console.log('Step 3')
          }
        });
}
and all I get in the console now is:
Step 1
Step 4 
and the localStorage line in success: function(msg) is not running too ( that obvious, seen as step 3 isnt getting done either.
 
    