Jelajahi Sumber

add hw 15 async2

serg155alternate 2 tahun lalu
induk
melakukan
b2891c3442

+ 5 - 5
HW14 await paradise/script.js

@@ -11,10 +11,10 @@ let message = document.querySelector('#message');
 let nick = document.querySelector('#nickname');
 let btn = document.querySelector('.btn');
 
-btn.addEventListener('click', () => {
+btn.addEventListener('click',async () => {
     nickName = nickname.value;
     userMessage = message.value;
-    sendMessage(nickName, userMessage);
+    await sendMessage(nickName, userMessage);
     getMasseges();
     message.value = '';
 });
@@ -137,7 +137,7 @@ function readMessage(msg) {
 //Stage 6
 //Прогуглить и разобраться с fetch и заменить внутренности jsonPost на код, использующий fetch вместо XMLHttpRequest. 
 
-async function jsonPost(url, data) {
+/* async function jsonPost(url, data) {
     let response = await fetch(url, {
         method: "POST",
         headers: {
@@ -147,9 +147,9 @@ async function jsonPost(url, data) {
       });
       console.log(response);
     if (response.ok) {
-        let json = await response.json();
+        let json = response.json();
         return json;
     } else {
         return new Error('jsonPost failed'+ response.status);
     }   
-}
+} */

+ 8 - 2
HW15 generator/index.html

@@ -5,14 +5,20 @@
     <meta charset="UTF-8">
     <meta http-equiv="X-UA-Compatible" content="IE=edge">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
-    <title>HW15 Generator
+    <title>HW15 Generator - Async/Await Homework 2
+
     </title>
     <link rel="stylesheet" href="style.css">
 </head>
 
 <body>
     <div class="container">
-       
+        <div class="wrapper">
+           <!--  <div class="green"></div>
+            <div class="yellow"></div>
+            <div class="red"></div> -->
+        </div>
+        
     </div>
     <script src="script.js"></script>
 </body>

+ 50 - 0
HW15 generator and async await 2/script.js

@@ -0,0 +1,50 @@
+//Async/Await Homework 2
+const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms))
+
+//Используя асинхронную функцию и бесконечный цикл, просимулируйте светофор:
+
+
+/* async function trafficLight(){
+    while (true){
+        document.querySelector('.green').style.backgroundColor = 'green';
+        document.querySelector('.red').style.backgroundColor = '';
+        await delay(3000);
+        document.querySelector('.green').style.backgroundColor = '';
+        document.querySelector('.yellow').style.backgroundColor = 'yellow'; 
+        await delay(500)
+        document.querySelector('.yellow').style.backgroundColor = ''; 
+        document.querySelector('.red').style.backgroundColor = 'red';
+        await delay(2000)
+    }
+}
+trafficLight(); */
+
+//Stage 2
+//Сделайте trafficLight более универсальной - добавьте в параметры DOM-элемент для отображения, 
+//а так же время работы каждого цвета
+
+
+async function trafficLight(rootElClass, greenDelay, redDelay, yellowDelay){
+    let root = document.querySelector(rootElClass);
+    for (let i = 0; i <3; i++){
+        let div = document.createElement('div');
+        div.style.backgroundColor = 'black';
+        root.append(div);
+    }
+    while (true){
+        root.children[0].style.backgroundColor = 'green';
+        root.children[2].style.backgroundColor = '';
+        await delay(greenDelay);
+        root.children[1].style.backgroundColor = 'yellow';
+        root.children[0].style.backgroundColor = '';
+        await delay(redDelay)
+        root.children[2].style.backgroundColor = 'red';
+        root.children[1].style.backgroundColor = '';
+        await delay(yellowDelay)
+    }
+   
+}
+trafficLight('.wrapper', 1000, 800, 2000);
+
+//domEventPromise
+//Реализуйте промисифицированную функцию, которая резолвит промис по событию в DOM:

+ 27 - 0
HW15 generator and async await 2/style.css

@@ -0,0 +1,27 @@
+*, html {
+    margin: 0;
+    padding: 0;
+}
+.container {
+    position: relative;
+    max-width: 1140px;
+    margin: 0 auto;
+    padding: 50px;
+}
+.wrapper{
+    display: flex;
+    flex-direction: column;
+    border: solid 3px black;
+    width: 70px;
+    align-items: center;
+    background-color: rgb(231, 220, 220);
+    box-shadow: black -5px 5px;
+}
+.wrapper div {
+    width: 50px;
+    height: 50px;
+    margin-bottom: 5px;
+    border-radius: 100%;
+    background-color: rgb(130, 128, 128);
+}
+

+ 0 - 42
HW15 generator/script.js

@@ -1,42 +0,0 @@
-//Closures and scopes
-
-async function jsonPost(url, data) {
-    let response = await fetch(url, {
-        method: "POST",
-        headers: {
-          'Content-Type': 'application/json'
-        },
-        body: JSON.stringify(data)
-      });
-    if (response.ok) {
-        console.log('work')
-        let json = await response.json();
-        console.log(json)
-        return json;
-    } else {
-         new Error('jsonPost failed'+ response.status);
-    }  
-}
-
-
-/* function jsonPost(url, data) {
-    return new Promise((resolve, reject) => {
-        var x = new XMLHttpRequest();
-        x.onerror = () => reject(new Error('jsonPost failed'))
-        //x.setRequestHeader('Content-Type', 'application/json');
-        x.open("POST", url, true);
-        x.send(JSON.stringify(data))
-
-        x.onreadystatechange = () => {
-            if (x.readyState == XMLHttpRequest.DONE && x.status == 200) {
-                resolve(JSON.parse(x.responseText))
-            } else if (x.status != 200) {
-                reject(new Error('status is not 200'))
-            }
-        }
-    })
-} */
-
-
-jsonPost('https://jsonplaceholder.typicode.com/posts', {func: 'addMessage', nick: "HellWords", message: 'AHHAAAH'}).then(res => console.log(res)
-)

+ 0 - 10
HW15 generator/style.css

@@ -1,10 +0,0 @@
-*, html {
-    margin: 0;
-    padding: 0;
-}
-.container {
-    position: relative;
-    max-width: 1140px;
-    margin: 0 auto;
-    padding: 50px;
-}