Skip to content

Advanced One

API Request

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h2>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nulla, tempore!</h2>
</body>
<script>
const requestUrl = "https://api.github.com/users/hiteshchoudhary";
const xhr = new XMLHttpRequest();
xhr.open('GET', requestUrl);
xhr.onreadystatechange = function(){
console.log(xhr.readyState);
if(xhr.readyState === 4){
const data = JSON.parse(this.responseText);
console.log(typeof data);
console.log(data.followers);
}
}
xhr.send();
</script>
</html>

Promises

const promiseOne = new Promise(function(resolve, reject) {
setTimeout(function(){
console.log('Async task is complete');
resolve();
}, 1000)
})
promiseOne.then(function(){
console.log("Promise consumed");
});
new Promise(function(resolve, reject){
setTimeout(function(){
console.log("Async task 2");
resolve();
}, 1000);
}).then(function(){
console.log("Async 2 resolved");
});
const promiseThree = new Promise(function(resolve, reject){
setTimeout(function(){
resolve({username: "chai", email: "chai@example.com"})
}, 1000)
});
promiseThree.then(function(user){
console.log(user);
});
const promiseFour = new Promise(function(resolve, reject){
setTimeout(function(){
let error = true;
if(!error){
resolve({username: "hitesh", password: "123"});
} else {
reject('ERROR: Something went wrong')
}
}, 1000)
})
promiseFour.then((user) => {
console.log(user);
return user.username
}).then((username) => {
console.log(username);
}).catch(function(error) {
console.log(error);
}).finally(() => console.log("The promise is either resolved or rejected"));
const promiseFive = new Promise(function(resolve, reject){
setTimeout(function(){
let error = true;
if(!error){
resolve({username: "Javascript", password: "123"})
} else {
reject('ERROR: JS went wrong')
}
}, 1000);
});
async function consumePromiseFive(){
try {
const response = await promiseFive
console.log(response);
} catch (error) {
console.log(error);
}
}
consumePromiseFive();
async function getAllUsers(){
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
const data = await response.json();
console.log(data);
} catch (error) {
console.log("E: ", error);
}
}
getAllUsers();
fetch('https://api.github.com/users/hiteshchoudhary')
.then((response)=> response.json())
.then((data) => {
console.log(data);
})
.catch((error) => console.log(error));
// promise.all