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>