Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 7780

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 60k
Author
Asked: November 28, 20242024-11-28T07:00:11+00:00 2024-11-28T07:00:11+00:00

Understanding Async JS

  • 60k

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'; 
Enter fullscreen mode Exit fullscreen mode

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'; 
Enter fullscreen mode Exit fullscreen mode

  • 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');  
Enter fullscreen mode Exit fullscreen mode

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");  
Enter fullscreen mode Exit fullscreen mode

javascriptprogrammingwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.