es6 async和await结合使用


async和await结合使用

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>async和await结合使用</title> </head> <body> <script>  function readData() { return new Promise((resolve, reject) => { //创建对象 const xhr = new XMLHttpRequest(); //初始化 xhr.open("GET", "http://www.example.com:88/ecmas6-11/data.json"); //发送 xhr.send(); //绑定事件 xhr.onreadystatechange = function () { //判断 if (xhr.readyState === 4) { //判断响应码 if (xhr.status >= 200 && xhr.status < 300) { resolve(xhr.response); } else { reject(xhr.status); } } } }); } function readData2() { return new Promise((resolve, reject) => { //创建对象 const xhr = new XMLHttpRequest(); //初始化 xhr.open("GET", "http://www.example.com:88/ecmas6-11/data2.json"); //发送 xhr.send(); //绑定事件 xhr.onreadystatechange = function () { //判断 if (xhr.readyState === 4) { //判断响应码 if (xhr.status >= 200 && xhr.status < 300) { resolve(xhr.response); } else { reject(xhr.status); } } } }); } function readData3() { return new Promise((resolve, reject) => { //创建对象 const xhr = new XMLHttpRequest(); //初始化 xhr.open("GET", "http://www.example.com:88/ecmas6-11/data3.json"); //发送 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 fn() { try{ let data = await readData(); let data2 = await readData2(); let data3 = await readData3(); data = JSON.parse(data); data2 = JSON.parse(data2); data3 = JSON.parse(data3); return new Promise((resolve,reject)=>{ resolve([...data,...data2,...data3]); }) }catch (e) { console.log('error' + e); } } const p2 = fn(); p2.then( value => { console.log(value); } ) </script> </body> </html>


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM