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

Menu