使用Promise封裝簡單Ajax方法

咳咳

一直都很喜歡使用原生的JavaScript,特別是不需要考慮兼容性的場景(雖然少得可憐)。可惜ECMAScript并沒有封裝好的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的錯誤。不過我不是特別喜歡這一做法,邏輯錯誤和網絡請求錯誤怎么能混為一談呢?

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容