利用promise封裝ajax,axios過程
阿新 • • 發佈:2019-02-09
封裝ajax
var url = 'https://hq.tigerbrokers.com/fundamental/finance_calendar/getType/2017-02-26/2017-06-10'; // 封裝一個get請求的方法 function getJSON(url) { return new Promise(function(resolve, reject) { var XHR = new XMLHttpRequest(); XHR.open('GET', url, true); XHR.send(); XHR.onreadystatechange = function() { if (XHR.readyState == 4) { if (XHR.status == 200) { try { var response = JSON.parse(XHR.responseText); resolve(response); } catch (e) { reject(e); } } else { reject(new Error(XHR.statusText)); } } } }) } getJSON(url).then(resp => console.log(resp));
封裝axios
function myGet(url, params) { return new Promise((resolve, reject) => { axios.get(url, params).then(function (response) { resolve(response.data) }) .catch(function (err) { reject(err) }) }) } myGet(url,params).then(function(data){console.log(data)}).catch(function(){})