promise改造ajax回调

52 阅读1分钟

回调函数

``

 var xhr = new XMLHttpRequest();
 xhr.open('get','http://httpbin.org/ip')
 xhr.addEventListener('load', function () {
console.log(xhr.response) // 响应体数据

// 知识点: 把JSON格式字符串 ==> 转成JS数据类型
// 语法: JSON.parse(JSON字符串)
// 返回值: JS数据类型
let result = JSON.parse(xhr.response)
console.log(result);
 })
xhr.send()

promise改造axios

基本套路

第一步:建立模板函数。这里的模板函数是指固定的套路:写一个空函数,在函数体中new 一个promise对象,并返回。

第二步:把异步功能写入构造函数中,根据实际来决定是否调用resolve,reject。

第三步:调用函数。通过fnName().then().catch() 结构来调用这个函数

let ajax = function () {
            return new Promise((resolve, reject) => {
                var xhr = new XMLHttpRequest();
                xhr.open('get', 'http://httpbin.org/ip')
                xhr.onload = function () {
                    resolve(xhr.responseText)
                }
                xhr.onerror = function () {
                    reject('请求接口错误')
                }
                xhr.send()
            })
        }
        ajax().then(res => {
            console.log(res)
        }).catch(err => {
            console.log(err)
        })