Help with using async

Hello,

I am tring to call to an API from my script, for some reason it does not wait for a response, it just moves past, anyone have any idea as to what I am doing wrong?

 async function checkForValid() {
     
    alert('gothere');
    let url = 'https://site.com/api/v2/customers/' + document.getElementById(cuid_id).value;
    let key = 'dafdsfas_dgsfgsdfgfdsfd_dsfsd';
    
     (async () => {
        let checkLogin = await fetch(url, {method:'GET', headers: {'Authorization': 'Basic ' + btoa(key + ':')}});
        
        data = (await checkLogin.json())
        
        alert(data);
    })(); 
    
    alert(data);
       
 }
 

I left in my test spots.

when i run this it gets to the ‘gothere’ but then just moves on by…

Thank you for any help.

Well that’s the definition of asynchronous. It wont block the main thread.

 async function checkForValid() {
     
    alert('gothere');
    let url = 'https://site.com/api/v2/customers/' + document.getElementById(cuid_id).value;
    let key = 'dafdsfas_dgsfgsdfgfdsfd_dsfsd';
    
     (async () => {
        let checkLogin = await fetch(url, {method:'GET', headers: {'Authorization': 'Basic ' + btoa(key + ':')}});
        
        data = (await checkLogin.json())
        
        alert(data);
    })(); 
    
    alert(data);
       
 }

… Seems to be redundant.

 async function checkForValid() {  
    alert('gothere');
    let url = 'https://site.com/api/v2/customers/' + document.getElementById(cuid_id).value;
    let key = 'dafdsfas_dgsfgsdfgfdsfd_dsfsd';    
    let checkLogin = await fetch(url, {method:'GET', headers: {'Authorization': 'Basic ' + btoa(key + ':')}});        
    data = await checkLogin.json();
    alert(data);       
 }

Probably should be then’ing rather than awaiting, but eh.
Keep an eye on your network tab, make sure you see the fetch go out and come back.

Why? Using await is much easier to read. The only thing you need to do is using try/catch if you use await. When you use then you should use fail.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.