es6 async 和 await 组合发送ajax请求

142 阅读1分钟
function sendAjax(url) {
    return new Promise((resolve,reject) => {
       const xhr = new XMLHttpRequest();
       xhr.open('get',url);
       xhr.send();
       xhr.onreadystatechange = function () {
           if(xhr.readyState === 4) {
               if(xhr.status>=200 && xhr.status < 300){
                     resolve(xhr.response);
               } else {
                     reject(xhr.status);
               }
           }
       }
    })
}

async function main() {
   let a = await sendAjax('https://api.apiopen.top/api/sentences');
    console.log(a);
}
main();

视频观看地址 www.bilibili.com/video/BV1uK…