В этой статье мы рассмотрим время отклика методов post на языке JavaScript. Целью данного исследования является определение наличия каких-либо изменений во времени отклика при использовании следующих 4 методов.

· Аксиос

· Axios с Async/Await

· Извлечение с помощью Async/Await

· Извлечь

В этом исследовании мы использовали компьютер под управлением Windows 11, оснащенный следующими установленными программами:

· Google Chrome версия 116.0.5845.188

· Сервер Json как REST API (https://github.com/typicode/json-server).

· Код Visual Studio версии 1.82.1

· Версия узла 18.17.1

· версия НПМ 9.6.7

Сначала мы создаем папку, а затем в ней создаются следующие файлы.

· логин.html

· логин.js

· логин.css

Login.html содержит следующий код:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">    
    <meta name="keywords" content="HTML, CSS, Responsive, JavaScript , JS, Exercise">
    <meta name="description" content="Website for exercise JavaScript">
    <meta name="author" content="Ahmad Mokhtari">         
    <link rel="shortcut icon" href="../img/icon-logo.ico" type="image/x-icon">     
    <title>Sign in</title>    
    <!-- css -->  
    <link rel="stylesheet" href="../css/main.css">
    <link rel="stylesheet" href="css/login.css"> 
    <!-- JavaScript -->
    <script src="../js/main.js"></script>
    <script src="../js/menu.js"></script>
    <script src="js/login.js"></script>
    <script src="js/axios/axios.js"></script>
    <!-- <script src="https://unpkg.com/axios/dist/axios.min.js"></script> -->
</head>
<body>

  <aside id="mySidenav" class="sidenav">
    <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
    <a href="../../index.html">Home</a>
    <script>menuFilter(menuItem,"jsClass");</script>    
  </aside>

  <main id="main">
    <span class="span" onclick="openNav()">&#9776; Menu</span>
    <section id="loginContainer" class="loginContainer">                
      <h1 id="loginHeader" class="loginHeader">Sign in</h1>
      <h1 id="postMethod" class="loginHeader" style="margin-top:-40px;padding:20px;font-size:12px;"></h1>
      <div id="postMethodButton" style="margin: auto;">
        <a class="loginBtn" onclick="selectPostMethod('axios')">Axios</a>
        <a class="loginBtn" onclick="selectPostMethod('axiosAsync')">Axios with Async</a>
        <a class="loginBtn" onclick="selectPostMethod('fetchAsync')">Fetch with Async</a>
        <a class="loginBtn" onclick="selectPostMethod('fetch')">Fetch</a>
      </div><br>
      <input class="inputText" id="username" placeholder="username" autocomplete="off">
      <input class="inputText" id="password" type="password" placeholder="password" autocomplete="off"><br><br>
      <div id="buttonContainer"style="margin: auto;">
        <a id="loginBtn" class="loginBtn" onclick="login()">Sign in</a>    
        <a id="signupBtn"class="loginBtn" onclick="signup()" style="transition: none;">Create account</a>
      </div>
      <br>
      <!-- Loader -->
      <div id="loader" style="display:none;margin: auto;text-align: center;">
      <div id="loaderIcon" class="loaderIcon"><div></div><div></div><div></div><div></div></div>
      <p id="loaderText" class="loaderText">Loading...</p>              
      </div>
      <p id="result" class="loaderText"></p>        
    </section>    
    <!-- Snackbar / Toast -->
    <div id="toast"></div>
  </main>
  <script>showCreateNewAccount(1)</script>  
</body>
</html>

Login.js содержит следующий код:

"use strict";

let isSignup = false; //is the user goto Create account page or not
let isUnique = true; //Unique ID for post into Database
let postMethod = 0;  // 1 for axios, 2 for async and 3 for fetch

// --------------------- Hide and Show Loader ------------------------------------------------------
function showLoader(isShow){
  if(isShow) document.getElementById("loader").style.display="block"; // Show Loader
  else document.getElementById("loader").style.display="none"; // Hide Loader
}

// --------------------- Hide and Show input element to force user for select Post method ----------
function showCreateNewAccount(state){
  switch (state){
    case 1: //Hide postMethodButton
      document.getElementById("postMethodButton").style.visibility="hidden";
      break;
    case 2: //Show postMethodButton and Hide all elements of Create New Account
      document.getElementById("postMethodButton").style.visibility="visible";
      document.getElementById("name").style.visibility="hidden";
      document.getElementById("mobile").style.visibility="hidden";
      document.getElementById("username").style.visibility="hidden";
      document.getElementById("password").style.visibility="hidden";
      document.getElementById("result").style.visibility="hidden";
      break;
    case 3: //Hide postMethodButton and Show all elements of Create New Account
      document.getElementById("postMethodButton").style.visibility="hidden";
      document.getElementById("name").style.visibility="visible";
      document.getElementById("mobile").style.visibility="visible";
      document.getElementById("username").style.visibility="visible";
      document.getElementById("password").style.visibility="visible";
      document.getElementById("result").style.visibility="visible";
  }
}

// ------------------------------------------- Snackbar / Toast ---------------------------
function toast(message) {  
  var toastDiv = document.getElementById("toast");
  toastDiv.innerHTML = message;
  toastDiv.className = "show";
  // After 3 seconds, remove the show class
  setTimeout(function(){
    toastDiv.className = toastDiv.className.replace("show", ""); 
  }, 3000);
}

// ------------------------------------------- Select Post Method ---------------------------------
function selectPostMethod(name){
  if(name==='axios'){
    postMethod = 1;
    document.getElementById("postMethod").textContent = "((Axios))";
    document.getElementById("postMethodButton").style.display="none"; 
    showCreateNewAccount(3);
  } else if(name==='axiosAsync'){  
    postMethod = 2;
    document.getElementById("postMethod").textContent = "((Axios with Async))";
    document.getElementById("postMethodButton").style.display="none";   
    showCreateNewAccount(3);
  } else if(name==='fetchAsync'){  
    postMethod = 3;
    document.getElementById("postMethod").textContent = "((Fetch with Async))";
    document.getElementById("postMethodButton").style.display="none";   
    showCreateNewAccount(3);
  } else if(name==='fetch'){  
    postMethod = 4;
    document.getElementById("postMethod").textContent = "((Fetch))";
    document.getElementById("postMethodButton").style.display="none";   
    showCreateNewAccount(3);
  }
}

// ----------------------------------------------- POST1 ------------------------------------------
// make it by axios with .then and .catch 
function post1(name,mobile,username,password){
  showLoader(true);
  const result = document.getElementById("result");  
  isUnique = true; //for run again the function, set it again to true
  
  // check the username is unique  
  axios.get("http://localhost:3000/account")
  .then((response)=>{
    showLoader(false);
    for(let data of response.data){
      if (data.username === username) {
        result.innerHTML = "username " + "<span>" + username + "</span>" + " is already taken";        
        isUnique = false;                
        isSignup = true;
        break;
      }       
    }  
    if(isUnique){
      // get last ID from database
      let lastId = response.data[response.data.length-1].id;                
      // Add new user
      const newId = +lastId + 1;
      showLoader(true);
      axios.post("http://localhost:3000/account",{
        "id": String(newId),
        "name": String(name),
        "mobile": String(mobile),
        "username": String(username),
        "password": String(password)
      })
      .then((response) => {
        showLoader(false);
        if(response.status === 201){
          toast("Your Account has successfully created");
          setTimeout(()=>{document.location.reload()},3000);
        } else {
          result.innerHTML = "<span>" + "Error :" + "</span><br>" + response.message + "<br>" + response.config.url;
        }
      }, (reject) => {
        showLoader(false);
        result.innerHTML = "<span>" + "Error :" + "</span><br>" + reject.message + "<br>" + reject.config.url;
        document.getElementById("buttonContainer").style.display="none";
        setTimeout(()=>{document.location.reload()},5000);
      });  
    } 
  })
  .catch((reject)=>{
    showLoader(false);
    result.innerHTML = "<span>" + "Error :" + "</span><br>" + reject.message + "<br>" + reject.config.url;
    document.getElementById("buttonContainer").style.display="none";
    setTimeout(()=>{document.location.reload()},5000);
  });
}  

// ----------------------------------------------- POST2 ------------------------------------------
// make it by async and await and axios
async function post2(name,mobile,username,password){
  showLoader(true);
  const result = document.getElementById("result");
  isUnique = true; //for run again the function, set it again to true  
  try{
    // check the username is unique  
    const datas = await axios.get("http://localhost:3000/account");
    showLoader(false);
    for(let data of datas.data){
      if (data.username === username) {
        result.innerHTML = "username " + "<span>" + username + "</span>" + " is already taken";        
        isUnique = false;                
        isSignup = true;
        break;
      } 
    }
    if(isUnique){
      // get last ID from database
      const lastId = datas.data[datas.data.length-1].id;      
      // Add new user
      const newId = +lastId + 1;
      showLoader(true);
      const post = await axios.post("http://localhost:3000/account",{
        "id": String(newId),
        "name": String(name),
        "mobile": String(mobile),
        "username": String(username),
        "password": String(password)
      });
      showLoader(false);
      if(post.status === 201){
        toast("Your Account has successfully created");
        // result.textContent = "Your Account has successfully created";
        setTimeout(()=>{document.location.reload()},3000);
      } else {
        result.innerHTML = "<span>" + "Error :" + "</span><br>" + response.message + "<br>" + response.config.url;
        setTimeout(()=>{document.location.reload()},5000);
      }      
    }                  
  }
  catch(error){
    showLoader(false);
    result.innerHTML = "<span>" + "Error :" + "</span><br>" + error.message + "<br>";
    setTimeout(()=>{document.location.reload()},5000);
  }
}  

// ----------------------------------------------- POST3 ------------------------------------------
// make it by fetch with async and await
async function post3JSON(data) {
  showLoader(true);
  const result = document.getElementById("result");
  try {
    const response = await fetch("http://localhost:3000/account", {
      method: "POST", // or 'PUT'
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
    });
    showLoader(false);

    // const result1 = await response.json();
    if(response.status===201){
      toast("Your Account has successfully created");
      document.getElementById("buttonContainer").style.display="none";
      setTimeout(()=>{document.location.reload()},5000);
    } else {
      result.innerHTML = "<span>" + "Error :" + "</span><br>" + response.statusText + "<br>" + response.status + "<br>" + response.url;
      document.getElementById("buttonContainer").style.display="none";
      setTimeout(()=>{document.location.reload()},5000);
    }
  } catch (error) {
    showLoader(false);
    result.innerHTML = "<span>" + "Error :" + "</span><br>" + error.message + "<br>";
    document.getElementById("buttonContainer").style.display="none";
    setTimeout(()=>{document.location.reload()},5000);
  }
}
 
async function post3(name,mobile,username,password){
  showLoader(true);
  const result = document.getElementById("result");
  isUnique = true; //for run again the function, set it again to true  
  try{
    // check the username is unique  
    const accounts = await fetch("http://localhost:3000/account");
    showLoader(false);
    let accountsJson = await accounts.json();          
    for(let account of accountsJson){
      if (account.username === username) {
        result.innerHTML = "username " + "<span>" + username + "</span>" + " is already taken";        
        isUnique = false;                
        isSignup = true;
        break;
      } 
    }
    if(isUnique){
      // get last ID from database
      const lastId = accountsJson[accountsJson.length-1].id;      
      // Add new user
      const newId = +lastId + 1;    
      const data = {
          "id": String(newId),
          "name": String(name),
          "mobile": String(mobile),
          "username": String(username),
          "password": String(password)        
        };
        post3JSON(data);
    }
  }
  catch(error){
    showLoader(false);
    result.innerHTML = "<span>" + "Error :" + "</span><br>" + error.message + "<br>";
    document.getElementById("buttonContainer").style.display="none";
    setTimeout(()=>{document.location.reload()},5000);
  }
}          

// ----------------------------------------------- POST4 ------------------------------------------
// make it by pure fetch 
function post4JSON(data) {
  showLoader(true);
  const result = document.getElementById("result");  
  fetch("http://localhost:3000/account", {
    method: "POST", // or 'PUT'
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(data),
  })
  .then((response)=>{
    showLoader(false);
    if(response.status===201){
      toast("Your Account has successfully created");
      document.getElementById("buttonContainer").style.display="none";
      setTimeout(()=>{document.location.reload()},5000);
    } else {
      result.innerHTML = "<span>" + "Error :" + "</span><br>" + response.statusText + "<br>" + response.status + "<br>" + response.url;
      document.getElementById("buttonContainer").style.display="none";
      setTimeout(()=>{document.location.reload()},5000);
    }
  })
  .catch((error)=>{
    showLoader(false);
    result.innerHTML = "<span>" + "Error :" + "</span><br>" + error.message + "<br>";
    document.getElementById("buttonContainer").style.display="none";
    setTimeout(()=>{document.location.reload()},5000);
  });
}
 
function post4(name,mobile,username,password){
  showLoader(true);
  const result = document.getElementById("result");
  isUnique = true; //for run again the function, set it again to true  
    // check the username is unique  
  fetch("http://localhost:3000/account")
  .then((response)=> response.json())
  .then((accountsJson) => {
    showLoader(false);
    for(let account of accountsJson){
      if (account.username === username) {
        result.innerHTML = "username " + "<span>" + username + "</span>" + " is already taken";        
        isUnique = false;                
        isSignup = true;
        break;
      } 
    }
    if(isUnique){
      // get last ID from database
      const lastId = accountsJson[accountsJson.length-1].id;      
      // Add new user
      const newId = +lastId + 1;    
      const data = {
        "id": String(newId),
        "name": String(name),
        "mobile": String(mobile),
        "username": String(username),
        "password": String(password)        
        };
      post4JSON(data);
    }
  })
  .catch((error)=>{
    showLoader(false);
    result.innerHTML = "<span>" + "Error :" + "</span><br>" + error.message + "<br>";
    document.getElementById("buttonContainer").style.display="none";
    setTimeout(()=>{document.location.reload()},5000);
  });  
}        

// ----------------------------------------------- Sign up ------------------------------------------
function signup(){  
  const loginHeader = document.getElementById("loginHeader");
  const username = document.getElementById("username");  
  const password = document.getElementById("password");
  const loginBtn = document.getElementById("loginBtn");
  const signupBtn = document.getElementById("signupBtn");      
  const loginContainer = document.getElementById("loginContainer");
  // run if the first time click on "Create account" button, after that this button change name to "Sign up"
  if (!isSignup){
    isSignup = true;
    username.value = ""  ;
    password.value = ""  ;    
    // add 2 input element for name and mobile number
    let nameInput = document.createElement("input");
    let mobileInput = document.createElement("input");
    nameInput.className="inputText";
    nameInput.id="name";
    nameInput.placeholder="Name and Family";
    nameInput.setAttribute("autocomplete","off");
    mobileInput.className="inputText";
    mobileInput.id="mobile";
    mobileInput.placeholder="Mobile Number";  
    mobileInput.setAttribute("autocomplete","off");
    loginContainer.insertBefore(mobileInput,username);
    let mobile = document.getElementById("mobile");    
    loginContainer.insertBefore(nameInput,mobile);
    loginBtn.style.display = "none" ;
    loginHeader.textContent = "Create New Account";
    signupBtn.textContent = "Sign up";
    // hide "sign up" button so that the user completes all the Items first.
    document.getElementById("buttonContainer").style.visibility="hidden";
    document.getElementById("result").textContent = "Complete all the Items to create an Account";

    // AddEventListener for validate
    document.getElementById("name").addEventListener("keyup",function(e){validate(e)});
    mobile.addEventListener("keyup",function(e){validate(e)});
    username.addEventListener("keyup",function(e){validate(e)});
    password.addEventListener("keyup",function(e){validate(e)});        

    // wait for select post method
    showCreateNewAccount(2);
    
    // click on "sign up" button after that select the Post Method
  } else if (isSignup){
    isSignup = false;
    const name = document.getElementById("name");
    const mobile = document.getElementById("mobile");
    switch (postMethod){
      case 1:
        post1(name.value.trim(),mobile.value.trim(),username.value.trim(),password.value.trim());
        break;
      case 2:
        post2(name.value.trim(),mobile.value.trim(),username.value.trim(),password.value.trim());
        break;
      case 3:
        post3(name.value.trim(),mobile.value.trim(),username.value.trim(),password.value.trim());
        break;
      case 4:
        post4(name.value.trim(),mobile.value.trim(),username.value.trim(),password.value.trim());
    }
  } 
}

Login.css содержит следующий код:

:root{
  --gold : rgb(237, 167, 32);
  --gold70 : rgba(237, 169, 32, 0.7);
}

.loginContainer{
  display: flex;
  justify-content: center;
  flex-direction: column;
  width: 40%;
  margin: auto;    
  border: 1px solid black;
  box-sizing: border-box;
  box-shadow: 3px 4px 12px 1px rgba(0, 0, 0, 0.25);
  padding: 30px 20px;    
  margin-top: 50px;    
  transition: 0.4s;
}

.loginContainer:hover{
  width: 41%;     
  border: 1px solid #CD853F;
}

.loginHeader{
  font-family: 'Salsa', cursive;  
  color:var(--gold);
}

.inputText{
  margin: auto;
  padding: 10px 20px;  
  text-align: left;  
  width: 70%;
  margin-top: 20px;      
}

.loginBtn{
  font-family: 'Salsa', cursive;  
  font-size: 16px; 
  color:var(--gold);
  text-decoration: none;
  border: 1px solid black;
  background-color: #202020;  
  text-align: center;
  padding: 10px;  
  cursor: pointer;
  margin-left: 20px; 
  transition: 0.4s; 
}
.loginBtn:active {  
  background-color: #101010;  
  padding: 12px;
}
.loginBtn:hover {
  color:#e8eaed;
  border: 1px solid #9aa0a6;    
  font-size: 18px; 
}

Затем мы создали файл JSON как файл базы данных следующим образом:

jsonDB.json

{
   "account": [
    {
      "id": "1",
      "name": "Katheryn Shaw",
      "mobile": "09121000935",
      "username": "[email protected]",
      "password": "Ss@12345"
    },
    {
      "id": "2",
      "name": "Leo Simpson",
      "mobile": "09353300330",
      "username": "[email protected]",
      "password": "Ll@12345"
    }
  ]
}

После этого откройте cmd.exe и запустите сервер Json с помощью этой команды. Обратите внимание, что нам нужно держать cmd.exe открытым до завершения проверки.

json-server --watch jsonDB.json

Теперь откройте файл login.html в Google Chrome и нажмите кнопку создать аккаунт.

Мы можем выбрать любой из 4 методов и увидеть результат времени ответа в DevTools (Ctrl+Shift+j) Google Chrome (вкладка «Сеть»).

Чтобы проверить как можно точнее, мы выполняем каждую функцию 3 раза.

Обратите внимание, что входная информация для всех функций одинакова и включает в себя следующую информацию:

Имя: Мелиса Ривера

Мобильный: 0018006427676

Имя пользователя: [email protected]

Пароль: Mm@12345

Мы добавили 1, 2 или 3 в конец имени пользователя, чтобы сделать его уникальным.

Полученные результаты :

Результаты для функции Axios следующие:

Результаты для функции Axios с Async/Await следующие:

Результаты для функции Fetch with Async/Await следующие:

Результаты для функции Fetch следующие:

Изучая приведенные выше таблицы, можно увидеть две вещи:

Во-первых, размер отправляемой информации одинаков во всех методах Post.

Во-вторых, время отклика каждой функции разное, что на первый взгляд может привести к выводу, что каждая функция выполняет свою публикацию с разной скоростью. Но важно проверить состояние сервера базы данных (Json Server), у которого время ответа на каждый запрос варьируется, а состояние каждой функции следующее:

Аксиос:

Axios с Async/Await:

Извлечение с помощью Async/Await:

Принести :

что при объединении этих результатов возможен правильный и всесторонний анализ:

Как мы видим, убрав время ответа БД, время ответа всех функций стало равным 1, что говорит о том, что время ответа всех функций одинаковое.

Итак, по сути, я хочу вам сказать, что лучше использовать метод, который имеет самую простую и легкую отладку, а это, на мой взгляд, использование Axios с функцией Async/Await.

Также, если вы хотите протестировать самостоятельно, вы можете зайти на мой GitHub (https://github.com/pofnor/javascriptClassExercision) и проверить самостоятельно (проверьте login.html и login.js).