携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第12天点击查看活动详情。
Promise 问题
一、Promise 对象状态的方式:1、resolve 函数 2、reject 函数 3、抛出错误 throw
let p = new Promise((res, rej) => {
// 初始状态为 pending
// 1、resolve 函数
res('OK') // pending =》 fulfiled (resolve)
/* Promise {<fulfilled>: 'OK'} */
// 2、reject 函数
rej('err') // pending => reject
/* Promise {<rejected>: 'err'} */
// 3、抛出问题
throw '出问题了'
/* Promise {<rejected>: '出问题了'} */
})
console.log(p)
二、一个 Promise 指定多个成功 / 失败 回调函数,都会调用吗? :当 Promise 改变为对应状态时都会调用
三、改变 Promise 状态和指定回调还是农户谁先谁后? 都有可能,正常情况下先指定回调,再改变状态,但也可以先改变状态再指定回调。
- 1、先改变状态再指定回调:① 在执行器中直接调用 resolve / reject ② 延迟更长时间才调用 then()
- 2、什么时候才能得到数据: ① 如果先指定回调,当状态发生改变时,回调函数就会调用,得到数据 ② 如果先改变的状态,当指定回调时,回调函数就会调用,得到数据
四、Promise.then() 返回的新的 Promise 的结果状态由什么决定? 由 then() 指定的回调函数的结果决定:
- ① 如果抛出异常,新Promise 变为 reject,reason 为抛出的异常
- ② 如果返回非 Promise 的任意值,新 Promise 变为 resolve,value 为 返回值。
- ③ 如果返回的是另一个新的 Promise,此 promise 的结果就会成为新 Promise 的结果
五、Promise 串连多个操作任务:
- ① Promise 的 then() 返回一个新的 promise,可以开成 then() 的链式调用
- ② 通过 then 的链式调用串连多个 同步 / 异步任务
六、Promise 异常穿透
- ① 当使用 promise 的 then 链式调用时,可以在最后指定失败的回调
- ② 前面任何操作出了异常,都会传到最后失败的回调中处理
七、中断 Promise 链
- ① 当使用 Promise 的 then 链式调用时,在中间中断,不在调用后面的回调函数
- ② 方法:在回调函数中返回一个 pendding 状态的 promise 对象
let p = new Promise((res, rej) => {
setTimeout(() => {
res('ok')
}, 1000);
});
p.then(value => {
console.log(111);
// 只有返回一个 pendding 状态的 Promise 才能中断
return new Promise(() => { })
}).then(value => {
console.log(222);
}).then(value => {
console.log(333)
}).catch(reason => {
console.warn(reason)
})
// 输出结果: 111