anton123 2 år sedan
förälder
incheckning
eb2ba711a4
4 ändrade filer med 229 tillägg och 0 borttagningar
  1. 56 0
      Async, Await/Chat.html
  2. 34 0
      Async, Await/SWAPI Links.js
  3. 17 0
      Async, Await/domEventPromise.js
  4. 122 0
      Промисы.js

+ 56 - 0
Async, Await/Chat.html

@@ -0,0 +1,56 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+	<meta charset="UTF-8">
+	<title>Title</title>
+</head>
+<body>
+	<input id="nick" type="text"><br>
+	<input id="message" type="text"><br>
+	<button id="button" type="button" onclick=sendAndCheck()>Отправить</button>
+	<main id="main"></main>
+<script >
+
+	const jsonPost = (url, data) => {
+		return fetch(url, {method: 'POST',body: JSON.stringify(data)})
+		.then(result => {
+			if (result.status === 200) {
+				return result.json()
+			} else {
+				throw new Error('Error')
+			}
+		}).catch(error => {console.log(error)})
+	}
+	async function sendMessage(nick, message){
+		jsonPost("http://students.a-level.com.ua:10012", {func: 'addMessage', nick: nick, message: message})
+		.then(data => data)
+	}
+	
+
+	async function getMessages(){
+		jsonPost("http://students.a-level.com.ua:10012",{func: "getMessages", messageId: 0})
+		.then(data => {
+		let dataRevers = data.data.reverse()
+		document.getElementById("main").replaceChildren()
+			for(let el of dataRevers){
+				let div = document.createElement('div')
+				div.innerText= `${el.nick}: ${el.message}`
+				document.getElementById('main').append(div)
+			}	
+		})
+	}
+	getMessages()
+
+	async function sendAndCheck(){
+		sendMessage(document.getElementById("nick").value, document.getElementById("message").value)
+		await getMessages()
+	}
+
+	
+	function checkLoop(){
+		setInterval(()=>getMessages(),2000)
+	}
+	checkLoop()
+</script>
+</body>
+</html>

+ 34 - 0
Async, Await/SWAPI Links.js

@@ -0,0 +1,34 @@
+//SWAPI Links
+{
+    async function jsonTable (obj){
+        for(let el in obj){       
+            
+    
+            if(Array.isArray(obj[el])){
+                let i = 0
+                for(let elArr of obj[el]){
+                    async function btn (link){  
+                        return fetch(link)
+                        .then(res => res.json())
+                        .then(luke => obj[el][i]=luke)   
+                    }
+                    if(elArr.indexOf("https://swapi.dev")!== -1){
+                       await btn(elArr)
+                    }
+                    i++
+                }
+            }
+            if(obj[el].indexOf("https://swapi.dev")!== -1){
+                fetch(obj[el])
+                .then(res => res.json())
+                .then(luke => obj[el]=luke)
+            }
+        }
+        console.log(obj)
+    }
+    fetch('https://swapi.dev/api/people/20')
+    .then(res => res.json())
+    .then(luke =>jsonTable(luke))
+}
+
+

+ 17 - 0
Async, Await/domEventPromise.js

@@ -0,0 +1,17 @@
+//domEventPromise
+{
+    let knopka = document.createElement('button')
+    knopka.innerText='Кнопка'
+    document.body.append(knopka)
+    function domEventPromise(element, eventName) {
+        function executor(resolve) {
+            function handler(event) {
+                element.removeEventListener(eventName, handler);
+                resolve(event);
+            }
+            element.addEventListener(eventName, handler);
+        }
+        return new Promise(executor);
+    }
+    domEventPromise(knopka, 'click').then(e => console.log('event click happens', e));
+}

+ 122 - 0
Промисы.js

@@ -0,0 +1,122 @@
+//fetch basic
+{
+    function jsonTable (dom,json){
+        let table = document.createElement('table')
+        table.border = "1"
+        dom.append(table)
+        for(let el in json){
+            let tr = document.createElement('tr')
+            let td1 = document.createElement('td')
+            let td2 = document.createElement('td')
+            td1.innerText= el
+            td2.innerText= json[el]
+            table.append(tr)
+            tr.append(td1,td2)
+        }
+    }
+
+    fetch('https://swapi.dev/api/starships/12/')
+    .then(res => res.json())
+    .then(luke =>jsonTable(document.body,luke))
+}
+
+
+//fetch improved
+{
+    function jsonTable (dom,json){
+        let table = document.createElement('table')
+        table.border = "1"
+        dom.append(table)
+        for(let el in json){
+            let tr = document.createElement('tr')
+            let td1 = document.createElement('td')
+            let td2 = document.createElement('td')
+            
+            td1.innerText= el
+            td2.innerText= json[el]
+            table.append(tr)
+            tr.append(td1,td2)
+            function btn (link){
+                let button = document.createElement('button')
+                button.innerText='info'
+                button.onclick= function(){
+                    fetch(link)
+                    .then(res => res.json())
+                    .then(luke =>jsonTable(document.body,luke))
+                }
+                td2.append(button)
+            }
+
+            if(Array.isArray(json[el])){
+                for(let elArr of json[el]){
+                    if(elArr.indexOf("https://swapi.dev")!== -1){
+                        btn(elArr)
+                    }
+                }
+            }
+            if(json[el].indexOf("https://swapi.dev")!== -1){
+                btn(json[el])
+            }
+        }
+    }
+
+    
+    fetch('https://swapi.dev/api/starships/12/')
+    .then(res => res.json())
+    .then(luke =>jsonTable(document.body,luke))
+    
+}
+
+
+
+//race
+{
+    function delay(ms){ 
+        function executor(fulfill, reject){
+            setTimeout(() => fulfill(ms), ms)
+        }
+        return new Promise(executor) 
+    }
+
+    let promise1 = fetch("https://swapi.dev/api/films/1/")
+        .then(() => console.log(`promise ${Date.now()-startTimer} ms`))
+    let promise2 = delay(400)
+        .then(() => console.log("delay"))
+    let startTimer = Date.now()
+    Promise.race([promise1, promise2])
+        .then(result => result)
+}
+
+//Promisify: confirm
+{
+    function confirmPromise(text){
+        function executor(fulfill, reject) {
+            if (confirm(text)){
+                fulfill()
+            }
+            else{reject()}
+        }
+        return new Promise(executor)
+    }
+    
+    confirmPromise('Промисы это сложно?').then(() => console.log('не так уже и сложно'),
+                                               () => console.log('respect за усидчивость и внимательность'))
+}
+
+
+//Promisify: prompt
+{
+    function promptPromise(text){
+        function executor(fulfill, reject) {
+            let name = prompt(text)
+            if (name){
+                fulfill(name)
+            }
+            else{reject()}
+        } 
+        return new Promise(executor)
+    }
+    promptPromise("Как тебя зовут?").then(name => console.log(`Тебя зовут ${name}`), 
+                                          () => console.log('Ну зачем морозиться, нормально же общались'))
+}
+