Promise 基础知识

33 阅读1分钟

基本使用

resolve

image.png

reject

image.png

应用

image.png

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)
})

链式调用

  1. Promise 对象的 then 方法会返回一个全新的对象
  2. 后面的then方法就是为上一个then返回的Promise注册回调
  3. 前面的then方法中的返回值会作为后面then方法回调的参数
  4. 如果回调返回的是Promise,那么后面then方法的回调等待它的结束
image.png

并行处理

image.png