Browse Source

async_await_chat

Iryna Bolbat 2 years ago
parent
commit
09e20d43d2

+ 17 - 0
js_12_async_await_chat/index.html

@@ -0,0 +1,17 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+    <meta charset="UTF-8">
+    <meta http-equiv="X-UA-Compatible" content="IE=edge">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <link href="style.css" rel="stylesheet" type="text/css" />
+    <title>Document</title>
+</head>
+<body>
+    <input type="text" id="nick" placeholder="nick">
+    <input type="text" id="message" placeholder="message">
+    <button id="send">Send</button>
+    <div id="chat"></div>
+    <script src="main.js"></script>
+</body>
+</html>

+ 58 - 0
js_12_async_await_chat/main.js

@@ -0,0 +1,58 @@
+async 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'));
+            }
+        }
+    })
+}
+
+async function sendMessage(nick, message) {
+    jsonPost("http://students.a-level.com.ua:10012", {
+    func: 'addMessage', 
+    nick: nick, 
+    message: message,
+    author: 'chat'
+    });
+}
+
+const dateToDataTimeLocal = date => (date.getTime() - date.getTimezoneOffset() * 60000).toISOString().slice(0, -1);
+let timestamp = new Date();
+
+let nextMessageId = 0;
+
+async function getMessages() {
+    await jsonPost("http://students.a-level.com.ua:10012", { 
+        func: 'getMessages', 
+        messageId: nextMessageId 
+    }).then(res => {
+        res.data.forEach(el => {
+            let div = document.createElement('div');
+            div.innerHTML = `${el.nick} : ${el.message}:<br> ${timestamp.toGMTString()}`;
+            chat.prepend(div);
+            nextMessageId++;
+            console.log(nextMessageId);
+        });
+    });
+}
+
+send.onclick = async function sendAndCheck()  {  
+    sendMessage(nick.value, message.value);
+    getMessages();
+};
+
+async function checkLoop() {
+    await getMessages().then(() => delay(setTimeout (3000)).then(checkLoop));
+}
+
+checkLoop();

+ 4 - 0
js_12_async_await_chat/style.css

@@ -0,0 +1,4 @@
+button, input {
+    width: 100%;
+    font-size: 1.5em;
+}