// ДЗ: Промисы // задание 1 fetch basic { function displayJSONInTable(DOM, JSON) { // создаем таблицу let table = document.createElement('table'); // обрабатываем JSON и создаем строки таблицы for (let key in JSON) { let row = document.createElement('tr'); // создаем ячейку с названием свойства let keyCell = document.createElement('td'); keyCell.innerText = key; row.appendChild(keyCell); // создаем ячейку со значением свойства let valueCell = document.createElement('td'); valueCell.innerText = JSON[key]; row.appendChild(valueCell); // добавляем строку в таблицу table.appendChild(row); } // добавляем таблицу в DOM DOM.appendChild(table); } } { // Чтобы отобразить JSON в форме таблицы, нужно вызвать функцию displayJSON с соответствующими аргументами (Этот код сначала получает данные о Люке Скайвоке через запрос fetch, а затем отображает их в форме таблицы в контейнере body.): fetch('https://swapi.dev/api/people/1/') .then((res) => res.json()) .then((luke) => displayJSON(document.body, luke)); } // задание 2 fetch improved { function createTable(parent, data) { // Создаем таблицу const table = document.createElement('table'); // Создаем строку с заголовками const thead = document.createElement('thead'); const headRow = document.createElement('tr'); for (const key in data) { const th = document.createElement('th'); th.textContent = key; headRow.appendChild(th); } thead.appendChild(headRow); table.appendChild(thead); // Создаем тело таблицы const tbody = document.createElement('tbody'); for (const key in data) { const td = document.createElement('td'); const value = data[key]; if (typeof value === 'string' || Array.isArray(value)) { if (value.includes('https://swapi.dev/api/')) { // Создаем кнопку const button = document.createElement('button'); button.textContent = 'Load data'; button.addEventListener('click', () => { fetch(value) .then((res) => res.json()) .then((newData) => { // Очищаем тело таблицы while (tbody.firstChild) { tbody.removeChild(tbody.firstChild); } // Обновляем таблицу createTable(tbody, newData); }); }); td.appendChild(button); } else { td.textContent = value; } } else { // Создаем таблицу с вложенными данными createTable(td, value); } tbody.appendChild(td); } table.appendChild(tbody); // Добавляем таблицу в родительский элемент parent.appendChild(table); } } // задание 3 race { const delay = (time) => new Promise((resolve) => setTimeout(resolve, time)); const myFetch = (url) => fetch(url).then((res) => res.json()); Promise.race([delay(Math.random() * 1000), myFetch('https://swapi.dev/api/people/1/')]).then( (result) => { if (result.name) { console.log(`myFetch was faster`); } else { console.log(`delay was faster`); } }, ); } // задание 4 Promisify: confirm { function confirmPromise(text) { return new Promise((resolve, reject) => { if (confirm(text)) { resolve(); } else { reject(); } }); } confirmPromise('Промисы это сложно?').then( () => console.log('не так уже и сложно'), () => console.log('respect за усидчивость и внимательность'), ); } // задание 5 Promisify: prompt { function promptPromise(text) { return new Promise((resolve, reject) => { const response = prompt(text); if (response) { resolve(response); } else { reject(); } }); } promptPromise('Как тебя зовут?') .then((name) => console.log(`Тебя зовут ${name}`)) .catch(() => console.log('Ну зачем морозиться, нормально же общались')); } // задание 6 Promisify: LoginForm { class LoginForm { constructor(parent) { this.parent = parent; } createForm() { return new Promise((resolve, reject) => { const form = document.createElement('form'); const loginInput = document.createElement('input'); loginInput.type = 'text'; loginInput.placeholder = 'Логин'; form.append(loginInput); const password = new Password(form, false); password.onChange = () => (loginButton.disabled = !(loginInput.value && password.getValue())); const loginButton = document.createElement('button'); loginButton.textContent = 'Войти'; loginButton.disabled = true; loginButton.addEventListener('click', () => { resolve({ login: loginInput.value, password: password.getValue() }); }); form.append(loginButton); this.parent.append(form); }); } } function loginPromise(parent) { const form = new LoginForm(parent); return form.createForm(); } loginPromise(document.body).then(({ login, password }) => console.log(`Вы ввели ${login} и ${password}`), ); }