js async/await code example

Example 1: async await

const data = async ()  => {
  const got = await fetch('https://jsonplaceholder.typicode.com/todos/1');
  
  console.log(await got.json())
}

data();

Example 2: javascript async script

<script async src="script.js"></script>

Example 3: async await

async function showAvatar() {
	// read
  	await setTimeout(resolve, 3000);
    // read next 3s
}

showAvatar();

Example 4: javscript async await explained

// Promise approach

function getJSON(){

    // To make the function blocking we manually create a Promise.
    return new Promise( function(resolve) {
        axios.get('https://tutorialzine.com/misc/files/example.json')
            .then( function(json) {

                // The data from the request is available in a .then block
                // We return the result using resolve.
                resolve(json);
            });
    });

}

// Async/Await approach

// The async keyword will automatically create a new Promise and return it.
async function getJSONAsync(){

    // The await keyword saves us from having to write a .then() block.
    let json = await axios.get('https://tutorialzine.com/misc/files/example.json');

    // The result of the GET request is available in the json variable.
    // We return it just like in a regular synchronous function.
    return json;
}