基本使用
resolve
reject
应用
function ajax (url) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest()
xhr.open('GET',url)
xhr.responseType = json
xhr.onload = function (){
if (this.status ==200) {
resolve( this.response )
} else {
reject(new Error(this.statusText))
}
}
xhr.send()
})
}
ajax('/api/users.json').then(function(res){
console.log(res)
},function(error){
console.log(error)
})
链式调用
- Promise 对象的 then 方法会返回一个全新的对象
- 后面的then方法就是为上一个then返回的Promise注册回调
- 前面的then方法中的返回值会作为后面then方法回调的参数
- 如果回调返回的是Promise,那么后面then方法的回调等待它的结束