const p = document.querySelector('.p'); setTimeout(function(){ p.textContent = "Welcome to JS"; }, 3000); // C/b executes after duration. p.style.color = 'red';
Ex. Setting source of an img is an async operation, while rest of the code is running. Once the image is loaded completely, a load event will be emitted by JS for which we can listen. const img = document.querySelector('.cat'); img.src = 'cat.jpg' img.addEventListener('load',function(){ img.classList('fadeIn'); }); p.style.width = '300px';
# First API Call: Older way of doing AJAX using XHR. Modern way uses fetch API. - CORS need to be Yes/Unknown to access 3rd party APIs from our code. - AJAX call is done in the background, while the rest of the code keeps running which makes it non-blocking. - Hence, register a callback for the load event on request object. - Request is sent in the background, when its complete 'load' event will be fired. As soon data arrives, Callback fn will be called. HTML: <main class="container"> <div class="countries"> </div> </main> JS: const getCountryData = function(country){ const btn = document.querySelector('.btn-country'); const countriesContainer = document.querySelector('.countries'); // 1. request created const request = new XMLHttpRequest(); // 2.request opened request.open("GET", `https://restcountries.com/v3.1/name/${country}`); // 3. request sent request.send(); // 4. When data arrives, load event will be fired & below C/b will be invoked. // 5. response arrives in the property responseText of request object in JSON i.e big string of text will be received from AJAX call which needs to be converted to JS object. // 6. Convert JSON to JS. request.addEventListener("load", function () { // console.log(this); this refers to request object here. 'this' can be replaced with request object. // console.log(this.responseText); will only be set when data has arrived. // Both lines yield same result below. //const [ data ] = JSON.parse(this.responseText); const data = JSON.parse(this.responseText)[0]; console.log(data); const html = `<article class="country"> <img src=${data.flags.svg} alt="" class="country__img"> <div class="country__data"> <h3 class="country__name">${data.name.common}</h3> <h4 class="country__region">${data.region}</h4> <p class="country__row"><span>${(+data.population / 1000000).toFixed(1)}</span> mn</p> <p class="country__row"><span>${data.languages[Object.keys(data.languages)[0]]}</span></p> <p class="country__row"><span>${data.currencies[Object.keys(data.currencies)[0]].name}</span></p> </div> </article>`; countriesContainer.insertAdjacentHTML('beforeend', html); countriesContainer.style.opacity = 1; }); }; // All AJAX calls are happening in parallel getCountryData('usa'); getCountryData('russia'); getCountryData('germany'); getCountryData('brazil'); getCountryData('india');
// This below triangular shape denotes callback hell. Makes code hard to maintain. // GPP: Code which is hard to understand is bad code, hence difficult to add features // Promises help us to resolve this Callback Hell problem. setTimeout(() => { console.log("1 sec passed"); setTimeout(() => { console.log("2 sec passed"); setTimeout(() => { console.log("3 sec passed"); setTimeout(() => { console.log("4 sec passed"); setTimeout(() => { console.log("5 sec passed"); }, 1000); }, 1000); }, 1000); }, 1000); }, 1000); // Get the neighbouring countries const renderCountry = function (data) { const btn = document.querySelector(".btn-country"); const countriesContainer = document.querySelector(".countries"); const html = `<article class="country"> <img src=${data.flags.svg} alt="" class="country__img"> <div class="country__data"> <h3 class="country__name">${data.name.common}</h3> <h4 class="country__region">${data.region}</h4> <p class="country__row"><span>${(+data.population / 1000000).toFixed( 1 )}</span> mn</p> <p class="country__row"><span>${ data.languages[Object.keys(data.languages)[0]] }</span></p> <p class="country__row"><span>${ data.currencies[Object.keys(data.currencies)[0]].name }</span></p> </div> </article>`; countriesContainer.insertAdjacentHTML("beforeend", html); countriesContainer.style.opacity = 1; }; const getNeighbours = function (country) { const request = new XMLHttpRequest(); request.open("GET", `https://restcountries.com/v3.1/name/${country}`); request.send(); request.addEventListener("load", function () { const [data] = JSON.parse(this.responseText); console.log(data); renderCountry(data); const [neightbour] = data.borders; if(!neightbour) return; // request2 is Dependent on request1 as its invoke after request1. request2 will its own event listener. const request2 = new XMLHttpRequest(); request2.open("GET", `https://restcountries.com/v3.1/alpha/${data.borders}`); request2.send(); request2.addEventListener("load", function () { const [data2] = JSON.parse(this.responseText); console.log(data2); renderCountry(data2); }); }; getNeighbours("italy");
The above is the detailed content of Understanding Async JS. For more information, please follow other related articles on the PHP Chinese website!