- 嵌套使用方式是食用promise最常见的误区
function ajax (url) {
return new Promise(function (resolve, reject) {
let xhr = new XMLHttpRequest()
xhr.open('GET', url)
xhr.responseType = 'json'
xhr.onload = function () {
if (this.status + '' === '200') {
resolve(this.response)
console.log(this.response)
} else {
reject(new Error(this.responseText))
console.log(this.responseText)
}
}
xhr.send()
})
}
ajax('./ajaxTest.json')
// promise嵌套使用误区, 这种嵌套使用其实就是借助promise.then的链式调用的特点, 但是没有保证异步任务的扁平化
ajax(url).then(res => {
ajax(res).then(user => {
ajax(user.name).then(result => {
console.log(result)
})
})
})