Asynchronous
Asynchronous (비동기)
- Asynchronous code is executed after a task that runs in the "background" finishes
- Asynchronous code is non-blocking
- Execution doesn't wait for an asynchronous task to finish its work.
- Asynchronous literally means not ocurring at the same time.
- Only certain functions such as setTimeout work in an asynchronous way.
- Callback function OR an event listeners alone do not make code asynchronous.
// Example : Timer with callback
const p = document.querySelector('.p');
setTimeout(function () { // asynchronous
p.textContent = 'My name is Yonee';
}, 5000);
p.style.color = 'red';
// callback function will run after timer
// Example
const img = document.querySelector('.dog');
img.src = 'dog.jpg';
img.addEventListener('load', () => {
img.classList.add('fadeIn');
});
p.style.width = '300px';
AJAX
- Asynchronous JavaScript And XML : Allows us to communicate with remote web servers in an asynchronous way. With AJAX calls, we can request data from web servers dynamically.
API
- Application Programming Interface : Piece of software that can be used by another piece of software, in order to allow applications to talk to each other.
- DOM API, Geolocation API, Own Class API, "Online API"...
JSON
: most popular api data format.
AJAX Calls
- end point : URL that we need.
Countries
'use strict';
const btn = document.querySelector('.btn-country');
const countriesContainer = document.querySelector('.countries');
// old school way
const getCountryData = 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); // this = request
const html = `
<article class="country">
<img class="country__img" src="${data.flags.png}" />
<div class="country__data">
<h3 class="country__name">${data.name.common}</h3>
<h4 class="country__region">${data.region}</h4>
<p class="country__row"><span>👫</span>${(
+data.population / 1000000
).toFixed(1)}</p>
<p class="country__row"><span>🗣️</span>${
Object.values(data.languages)[0]
}</p>
<p class="country__row"><span>💰</span>${Object.keys(data.currencies)}</p>
</div>
</article>
`;
countriesContainer.insertAdjacentHTML('beforeend', html);
countriesContainer.style.opacity = 1;
});
};
getCountryData('portugal');
getCountryData('peru');
getCountryData('france');