Promise - And XMLHTTPRequest
محتوى الدرس
main.js
// Without Promise
function getFirstRepo(apiURL) {
let myRequest = new XMLHttpRequest();
myRequest.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
/*
Ready State => The Status Of The Request
[0] Request Not Initialized
[1] Server Connection Established
[2] Request Recieved
[3] Processing Request
[4] Request Is Finished And Response Is Ready
Status => Response Status Code
[200] Ok
[404] Not Found
*/
// console.log(this.responseText);
console.log(JSON.parse(this.responseText)[0].name);
}
};
// XMLHttpRequest.open(Method, URL, Async, User, Pass)
myRequest.open("GET", apiURL, true);
// Send The Request
myRequest.send();
}
getFirstRepo("https://api.github.com/users/ElzeroWebSchool/repos");
// With Promise
const getFirstRepo = (apiURL) => {
return new Promise((resolve, reject) => {
let myRequest = new XMLHttpRequest();
myRequest.onload = function () {
if (this.readyState === 4 && this.status === 200) {
resolve(JSON.parse(this.responseText)[0].name);
} else {
reject(Error(this.statusText));
}
};
myRequest.open("GET", apiURL, true);
myRequest.send();
});
};
getFirstRepo("https://api.github.com/users/ElzeroWebSchool/repos").then(
(result) => {
let newElement = document.createElement("div");
let elementText = document.createTextNode(result);
newElement.appendChild(elementText);
document.body.appendChild(newElement);
},
(error) => console.log(error)
);