Home  >  Article  >  Web Front-end  >  Understanding Async JS

Understanding Async JS

王林
王林Original
2024-09-01 21:07:111021browse

Understanding Async JS

Goal of Async JS: To deal with long running tasks which run in the background

  • Usecase: Fetch data from remote servers via AJAX calls.
  • Ex. Setting source of an img, Timers, Promises, Fetch API, Async-Await, Geolocation API, Error-Handling.

Sync Code:

  • Executed line by line in sequence in which its written by thread of execution which is part of execution context.
  • Dis: When one line of code takes long time to execute like an AJAX call, D/b access, alert window etc. which blocks code execution until its completed.

Async Code

  • Timer runs in the background without blocking code i.e doesn't block the main thread of execution.
  • Async code is executed after a task that runs in the background finishes.
  • Execution doesn't wait for an Async task to finish its work.
  • Async - Not occuring at the same time.
  • A callback doesn't make the code automatically async. Ex. An array map method accpets the callback, but it doesn't make the code async. Only certain functions like timers work in async way, but not all callbacks.
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';
  • Event listeners alone do not make the code async. Ex a button click listener is not doing any work in the background. Hence, no async behavior is involved.

AJAX

  • allows us to communicate with remote web servers in an async way.
  • data is requested from web servers dynamically using AJAX calls.

API

  • Software used by another s/w enabling communication b/w Apps.
  • Ex. DOM API, Geoloaction API etc. are all self contained pieces of software which allow softawres to interact with them
  • We can make implement an API by using class and making some methods public.
  • Online API : Application running on a server, that receives requests for data, and sends back data as a response.
  • APIs are build using backend development or use 3rd party APIs which are made available for us by other devs for free.
  • Ex. There are sample APIs for almost everything.
  • Earlier XML was used, now only JSON is used which is a JS object converted to a string.
# 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');

Callback Hell:

  • Chaining AJAX requests will make them work in order i.e second request will be generated after first was completed.

- Caused due to nested callbacks defined for nested AJAX calls which needs to be made in sequence.

// 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn