callback hell
回调地域的产生
$.get(url1, (data1) => {
console.log(data1);
$.get(url2, (data2) => {
console.log(data2);
$.get(url3, (data2) => {
console.log(data3);
// ...
})
})
})
promise链式调用来解决
function loadImg(src) {
return new Promise(
(resolve, reject) => {
const img = document.createElement('img')
img.onload = () => {
resolve(img)
}
img.onerror = () => {
const err = new Error(`图片加载失败 ${src}`)
reject(err)
}
img.src = src
}
)
}
const url1 = 'https://forguo.cn/imgs/logo.png'
const url2 = 'https://forguo.cn/imgs/logo.png'
loadImg(url1).then(img1 => {
console.log(img1.width)
return img1 // 普通对象
}).then(img1 => {
console.log(img1.height)
return loadImg(url2) // promise 实例
}).then(img2 => {
console.log(img2.width)
return img2
}).then(img2 => {
console.log(img2.height)
}).catch(ex => console.error(ex))
手写Promise
应用
封装一个ajax
// ajax封装
const request = function (params) {
return new Promise((resolve, reject) => {
const {
method = 'get',
url,
data
} = params;
const xhr = new XMLHttpRequest();
xhr.open(method, url, true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8')
xhr.onreadystatechange = function () {
/**
* readyState
* 0:还没调用
* 1:载入(正在发送)
* 2:载入完成
* 3:解析响应内容
* 4:解析完成
*/
if (xhr.readyState == 4) {
/**
* http状态码
* 2XX 成功返回
* 3XX 重定向
* 4XX 客户端错误
* 5XX 服务端错误
*/
if (xhr.status == 200) {
resolve(JSON.parse(xhr.responseText));
} else {
reject(xhr);
}
}
}
xhr.send(JSON.stringify(data) || null);
});
}
let submit = function () {
request({
method: 'post',
url: 'https://forguo.cn/api/common/wechat/sdk',
data: {
url: 'www',
}
}).then(res => {
console.log(res);
}, (err) => {
console.warn(err);
});
}