Encapsulate an ajax with Es6 and use promise callback

how to encapsulate an ajax, callback with Es6 syntax, use promise callback

Es6
Oct.15,2021

Does

mean the original XmlHttpRequest?

function ajax(url,success,failure){
  let xmlhttp=new XMLHttpRequest();
  xmlhttp.onreadystatechange=function(){
    if(xmlhttp.readyState===4){
      switch(xmlhttp.status){
        case 200:{
          success(xmlhttp.responseText)
          break
        }
        default:{
          failure(xmlhttp.status)
          break
        }
      }
    }
  };
  xmlhttp.open("GET","url",true);
  xmlhttp.send(null);
}

function ajaxPromise(url){
  return new Promise(function(resolve,reject){
      ajax(url,resolve,reject)
  })
}

ajaxPromise("https://www.baidu.com")
  .then(function(data){
  console.log(data)
})

Note: it is best to understand the idea of Promise . Promise is not a new ajax , but an idea of dealing with asynchronous transaction flow. See demo below, online source code: http://live.datatables.net/ra.

.
new Promise(function(resolve, reject){
  setTimeout(function(){
    resolve("timeout")
  },3000)
}).then(function(data){
  console.log(data)
})

console.log("here")

just use axios or fetch directly

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3f023-4f0c2.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3f023-4f0c2.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?