Skip to content
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Week2 Homework promise added
  • Loading branch information
haha1906 committed Sep 25, 2019
commit d2a83c9d0dc0d55068e85f2bf5dfd2f423a75e67
34 changes: 19 additions & 15 deletions homework/index.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
'use strict';

{
function fetchJSON(url, cb) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'json';
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status <= 299) {
cb(null, xhr.response);
} else {
cb(new Error(`Network error: ${xhr.status} - ${xhr.statusText}`));
}
};
xhr.onerror = () => cb(new Error('Network request failed'));
xhr.send();
function fetchJSON(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'json';
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status <= 299) {
resolve(xhr.response);
} else {
reject(new Error(`Network error: ${xhr.status} - ${xhr.statusText}`));
}
};
xhr.onerror = () => reject(new Error('Network request failed'));
xhr.send();
});
}

function createAndAppend(name, parent, options = {}) {
Expand Down Expand Up @@ -94,7 +96,8 @@
}

function fetchContributors(url, contributorsContainer) {
fetchJSON(url, (err, conts) => {
const promiseContributor = fetchJSON(url);
promiseContributor.then((conts, err) => {
if (err) {
createAndAppend('div', contributorsContainer, {
text: err.message,
Expand Down Expand Up @@ -135,7 +138,8 @@
}

function main(url) {
fetchJSON(url, (err, repos) => {
const promise = fetchJSON(url);
promise.then((repos, err) => {
const root = document.getElementById('root');
if (err) {
createAndAppend('div', root, {
Expand Down