From a9f0bfabb4c57f52c826dcba5f3a13048074bbdb Mon Sep 17 00:00:00 2001 From: EkaterinaBolvakina Date: Mon, 29 Apr 2024 15:19:28 +0200 Subject: [PATCH] commit --- Lesson21/Homework/index.js | 22 ++-- Lesson22/Lesson_Code/fetch/index.html | 15 +++ Lesson22/Lesson_Code/fetch/index.js | 68 ++++++++++++ Lesson22/Lesson_Code/fetch/test.json | 6 + Lesson22/Lesson_Code/index.html | 15 +++ Lesson22/Lesson_Code/index.js | 154 ++++++++++++++++++++++++++ 6 files changed, 269 insertions(+), 11 deletions(-) create mode 100644 Lesson22/Lesson_Code/fetch/index.html create mode 100644 Lesson22/Lesson_Code/fetch/index.js create mode 100644 Lesson22/Lesson_Code/fetch/test.json create mode 100644 Lesson22/Lesson_Code/index.html create mode 100644 Lesson22/Lesson_Code/index.js diff --git a/Lesson21/Homework/index.js b/Lesson21/Homework/index.js index 67021b0..7473b98 100644 --- a/Lesson21/Homework/index.js +++ b/Lesson21/Homework/index.js @@ -6,22 +6,22 @@ const delay = (value) => { if (typeof value !== 'number') { reject('The argument is not a number'); } else { - resolve(value ** 2); // resolve(value * value); + resolve(value ** 2); // resolve(value * value); } }, 5000); }); } delay(5) -.then(data => { - console.log(data); -}).catch(error => { - console.log('ERROR 1XX: ', error); -}) + .then(data => { + console.log(data); + }).catch(error => { + console.log('ERROR 1XX: ', error); + }) delay('5') -.then(data => { - console.log(data); -}).catch(error => { - console.log('ERROR 1XX: ', error); -}) \ No newline at end of file + .then(data => { + console.log(data); + }).catch(error => { + console.log('ERROR 1XX: ', error); + }) \ No newline at end of file diff --git a/Lesson22/Lesson_Code/fetch/index.html b/Lesson22/Lesson_Code/fetch/index.html new file mode 100644 index 0000000..0db6271 --- /dev/null +++ b/Lesson22/Lesson_Code/fetch/index.html @@ -0,0 +1,15 @@ + + + + + + + Document + + + + + + + + \ No newline at end of file diff --git a/Lesson22/Lesson_Code/fetch/index.js b/Lesson22/Lesson_Code/fetch/index.js new file mode 100644 index 0000000..6fb5002 --- /dev/null +++ b/Lesson22/Lesson_Code/fetch/index.js @@ -0,0 +1,68 @@ + +// -------- + +// работа с json - преобразование строки в объект js +// const data = JSON.parse(`{ +// "type": "general", +// "setup": "What kind of award did the dentist receive?", +// "punchline": "A little plaque.", +// "id": 255 +// } +// `); + + +// объект js преобразовали в json строку +// const pers = { +// name: 'bob', +// age: 22 +// } + +// const persJsonStr = JSON.stringify(pers); + +// console.log(persJsonStr); + + +// -------------- + +// запрос к паблик апи random_joke ( по умолчанию метод GEt ) +// fetch('https://official-joke-api.appspot.com/random_joke') +// .then(response => { +// return response.json(); +// }).then(data => { +// console.log(data); +// }); + +// обращение к гитхаб репозиторию +// let url1 = 'https://api.github.com/repos/SergeyRazin2014/ait-frontend/commits'; +let url1 = 'https://catfact.ninja/fact'; + +// fetch(url1) +// .then(response => { +// return response.json(); +// }).then(data => { +// console.log(data); +// }); + + +// const loadDagta = ()=>{ +// fetch(url1) +// .then(response => { +// return response.json(); +// }).then(data => { +// console.log(data); +// }); +// } + +// loadDagta(); + + + + + +const data = `{ + "type": "general", + "setup": "What kind of award did the dentist receive?", + "punchline": "A little plaque.", + "id": 255, + file: 'xcas2435gqsdagdfasdfasdfasdf' +}`; \ No newline at end of file diff --git a/Lesson22/Lesson_Code/fetch/test.json b/Lesson22/Lesson_Code/fetch/test.json new file mode 100644 index 0000000..423be56 --- /dev/null +++ b/Lesson22/Lesson_Code/fetch/test.json @@ -0,0 +1,6 @@ +{ + "type": "general", + "setup": "How do you make a hankie dance?", + "punchline": "Put a little boogie in it.", + "id": 128 +} \ No newline at end of file diff --git a/Lesson22/Lesson_Code/index.html b/Lesson22/Lesson_Code/index.html new file mode 100644 index 0000000..5c3f460 --- /dev/null +++ b/Lesson22/Lesson_Code/index.html @@ -0,0 +1,15 @@ + + + + + + + Document + + + + + + + + \ No newline at end of file diff --git a/Lesson22/Lesson_Code/index.js b/Lesson22/Lesson_Code/index.js new file mode 100644 index 0000000..8ab5367 --- /dev/null +++ b/Lesson22/Lesson_Code/index.js @@ -0,0 +1,154 @@ + +// пример функции с ключевым словом async (возвращает промис) +// const foo = async () => { +// return 'hello'; +// } + +// // вызов async функции +// foo() +// .then(data => { +// console.log(data); +// }) + +// ----------------- + +// пример с ключевым словом await +// const foo = async () => { +// const p = new Promise((resolve, reject) => { +// setTimeout(() => { +// resolve('hello'); +// }, 1000); + +// }); + +// // ждем выполнение промиса +// const res = await p; + +// console.log(res); +// } + +// foo(); + +// ---------------- + +// const p = new Promise((resolve, reject) => { +// setTimeout(() => { +// resolve('hello'); +// }, 1000); + +// }); + +// // ОШИБКА SyntaxError: await is only valid in async functions and the top level bodies of modules +// const res = await p; + +// -------------- + +// пример классической фнукции с ключ словом async +// async function foo() { +// const p = new Promise((resolve, reject) => { +// setTimeout(() => { +// resolve('hello'); +// }, 1000); + +// }); + +// const res = await p; +// console.log(res); +// } + +// foo(); + +// --------------- + +// +// const foo = async () => { +// const p = new Promise((resolve, reject) => { +// setTimeout(() => { +// resolve('hello'); +// }, 1000); + +// }); + +// // ждем выполнение промиса +// const res = await p; + +// return res; +// } + +// // результат вызова  asycn функции будет промисом не смотря на то что внутри нее вызывается await и возвращается примитивный результат +// const res = foo(); + +// ---------------- + +const loadDataAsync = async () => { + const promise1 = new Promise((resolve, reject) => { + setTimeout(() => resolve('Данные'), 1000); + }); + + return promise1; +} + +const analyseAsync = async (data) => { + const promise1 = new Promise((resolve, reject) => { + console.log(data); + setTimeout(() => resolve('Проанализированные данные '), 1000); + }); + + return promise1; +} + +const saveDataAsync = async (data) => { + const promise1 = new Promise((resolve, reject) => { + console.log(data); + setTimeout(() => resolve('Сохраненные сохранены '), 1000); + }); + return promise1; +} + +// вызов через then +// const main = () => { +// loadDataAsync() +// .then(data => { +// return analyseAsync(data); +// }).then(data => { +// return saveDataAsync(data); +// }).then(data => { +// console.log(data); +// }); +// } +// main(); + + +// вызов асинхронных функция похоже на синхронынй код +// const main = async () => { +// const data1 = await loadDataAsync(); +// const data2 = await analyseAsync(data1); +// const data3 = await saveDataAsync(data2); +// console.log(data3); +// } + +// main(); + +// ----------- + +const fooAsync = async () => { + + const promise1 = new Promise((resolve, reject) => { + // вызываем reject на промисе + setTimeout(() => reject('ERROR111'), 1000); + }); + + // если промис реджектит что-то - то await - выбросит исключение ( тут будет ошибка ) + // const result = await promise1; + + // чтобы обработать исключение нужно блок с await - завернить в try catch + try { + const result = await promise1; + console.log(result); + } catch (err) { + console.log('Произошла ошибка'); + } +} + + +