咳咳
一直都很喜歡使用原生的JavaScript,特別是不需要考慮兼容性的場景(雖然少得可憐)??上CMAScript并沒有封裝好的Ajax方法(其實也沒什么必要有),自己動手使用Promise
擼一個吧!
GET
function getJSON (url) {
return new Promise( (resolve, reject) => {
var xhr = new XMLHttpRequest()
xhr.open('GET', url, true)
xhr.onreadystatechange = function () {
if (this.readyState === 4) {
if (this.status === 200) {
resolve(this.responseText, this)
} else {
var resJson = { code: this.status, response: this.response }
reject(resJson, this)
}
}
}
xhr.send()
})
}
POST
function postJSON(url, data) {
return new Promise( (resolve, reject) => {
var xhr = new XMLHttpRequest()
xhr.open("POST", url, true)
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (this.readyState === 4) {
if (this.status === 200) {
resolve(JSON.parse(this.responseText), this)
} else {
var resJson = { code: this.status, response: this.response }
reject(resJson, this)
}
}
}
xhr.send(JSON.stringify(data))
})
}
咳咳
其實Promise
這家伙就是一個天然的try...catch
getJSON('/api/v1/xxx') // => 這里面是就try
.catch( error => {
// dosomething // => 這里就是catch到了error,如果處理error以及返還合適的值
})
.then( value => {
// dosomething // 這里就是final
})
不過有的朋友喜歡把catch
方法放在then
方法的后面,這樣就也可以監聽到then的錯誤。不過我不是特別喜歡這一做法,邏輯錯誤和網絡請求錯誤怎么能混為一談呢?