Promise关键问题


一、如何修改对象的状态

let p = new Promise ((resolve,reject)=>{
    
    
  //1.resolve函数
  // resolve('ok') //pending =>fulfilled(resolved)
  //2.reject 函数
  // reject('error');//pending =>rejected
  //3.抛出异常
  //throw '出问题了' //pending =>rejected
})

二、能否执行多个回调

问题:一个promise指定多个成功/失败回调函数,都会调用吗?
答案:当Promise改变为对应状态时都会调用(即状态非pending)

let p = new Promise ((resolve,reject)=>{
    
    
  resolve('ok')
})
//指定回调 -1
p.then((value)=>{
    
    
  console.log(value)
})

//指定回调 -2
p.then((value)=>{
    
    
  console.log(value)
})
//回调都会执行
let p = new Promise ((resolve,reject)=>{
    
    
})
//指定回调 -1
p.then((value)=>{
    
    
  console.log(value)
})

//指定回调 -2
p.then((value)=>{
    
    
  console.log(value)
})
//回调都不会执行

三、改变promise状态和指定回调函数谁先谁后

  1. 都有可能,正常情况下是先指定回调再改变状态,但也可以先改变状态再指定回调。
  2. 如何先改变状态再指定回调?
    1. 再执行器中直接调用 resolve()/reject()(同步任务)
    2. 延迟更长时间才调用then()
  3. 什么时候才能得到数据?
    1. 如果先指定的回调,那当状态发生改变时,回调函数会调用,得到数据
    2. 如果先改变的数据,那当指定回调时,回调函数就会调用,得到数据。

简单点就是then方法不管先执行还是后执行都会等状态改变时,才会调用回调函数

四、promise.then()返回的新promise的结果状态由什么决定?

  1. 简单表达:由then()指定的回调函数执行的结果决定
  2. 详细表达:
    1. 如果抛出异常,新promise变为reject,reason为抛出异常
    2. 如果返回的是非promise的任意值,新promise变为resolve,value为返回值
    3. 如果返回的是另一个新的promise,此promise的结果就会成为新promise的结果

五、promise异常穿透

  1. 当使用promise的then链式调用时,可以在最后指定失败的回调。
  2. 前面任何操作出了异常,都会传到最后失败的回调中处理

let p = new Promise ((resolve,reject)=>{
    
    
  reject('error')
})
//指定回调
p.then((value)=>{
    
    
    console.log(111)
}).then(value=>{
    
    
  console.log(222)
}).then(value=>{
    
    
  console.log(333)
}).catch(reason=>{
    
    
  console.warn(reason)
})
//不需要再每一个后面都写catch  只需要在最后一个后面写catch就可以了

六、中断promise链

  1. 当使用promise的then链式调用时,在中间中断,不在调用后面的回调函数
  2. 办法:在回调函数中返回一个pendding状态的promise对象
let p = new Promise ((resolve,reject)=>{
    
    
  resolve('ok')
})
//指定回调  现在只想输出111 不想输出222 333
p.then((value)=>{
    
    
    console.log(111)
    //有且只有一个方式可以终止promise链 return 一个pending状态的promise
    return new Promise(()=>{
    
    })
}).then(value=>{
    
    
  console.log(222)
}).then(value=>{
    
    
  console.log(333)
})

猜你喜欢

转载自blog.csdn.net/m0_58065010/article/details/129787261