Async/Await

Video

JavaScript Notes

JavaScript
    async function getUser( ){	// adding the keyword ‘async’ turns this into an asynchronous function (a Promise) 
        let counter = 0;
        let output = document.getElementById('output');
        let userid = Math.floor(Math.random( ) * 10) + 1;
        let url = 'https://jsonplaceholder.typicode.com/users/${userid}';
        /*** 
        fetch(url)
        .then(response => resonse.json( ))
        .then (data => {
            output.textContent += JSON.stringify(data, null, 2); 
            console.log(data);
        })
        output.textContent += 'REQUEST SENT ';
        ***/
    
        let response = await fetch (url); // adding ‘await’ waits for the request to finish before moving to the next line
        let data = await response.json( );

        output.textContent += 'REQUEST SENT'; 
        output.textContent += JSON.stringify(data, null, 2); 
        return 42;
    }
     
    let ret = getUser( ); 
    console.log(ret);