Promise的几个关键问题

时间:2025-02-13 16:55:00

1、如何改变promise的状态?

(1) resolve(value):如果当前是pending就会变成resolved

(2) reject(reason):如果当前是pending就会变成rejected

(3) 抛出异常:如果当前是pending就会变成rejected

2、一个promise指定多个成功/失败回调函数,都会调用吗?

当promise改变为对应状态时都会调用

const p=new Promise((resolve,reject)=>{
    throw 3
})
p.then(
value=>{},
    reason=>{console.log('reason',reason)}
)
p.then(
value=>{},
    reason=>{console.log('reason2',reason)}
)

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

(1) 都有可能,正常情况下是先指定回调再改变状态,但也可以先改状态再指定回调

(2) 如何先改变状态再指定回调?

在执行器中直接调用resolve()/reject()

延迟更长时间才调用then()

(3) 什么时候才能得到数据?

如果先指定的回调,那当状态改变时,回调函数就会调用,得到数据

如果先改变状态,那当指定回调时,回调函数就会调用,得到数据

new Promise((resolve,reject)=>{
    setTimeout(()=>{
        resolve(1)//后改变状态(同时指定数据),异步执行回调函数
    },1000)
}).then(//先指定回调函数,保存当前指定的回调函数
value=>{},
    reason=>{console.log('reason',reason)}
    
)
//========
new Promise((resolve,reject)=>{
   
        resolve(1)//先改变状态(同时指定数据)
 
}).then(//后指定回调函数,异步执行回调函数
value=>{},
    reason=>{console.log('reason',reason)}
    
)

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

(1) 简单表达:由then()指定的回调函数执行的结果决定

(2) 详细表达:

如果抛出异常,新promise变为rejected,reason为抛出的异常

如果返回的是非promise的任意值,新promise变为resolved,value为返回值。

如果返回的是另一个新的promise,此promise的结果就会成为新的promise结果

new Promise((resolve,reject)=>{
    resolve(1)
}).then(value=>{
    console.log('onResolved1()',value)//1  相当于返回了undefined
},reason=>{console.log('onRejected1()',reason)}
).then(
value=>{console.log('onResolve2()',value)},
    reason=>{console.log('onRejected2()',reason)}
)
//打印onResolved1() 1
//onResolved2() undefined

5、promise如何串联多个操作任务?

(1) promise的then()返回一个新的promise,可以看成then()的链式调用。

(2) 通过then的链式调用串联多个同步/异步任务

在then里面执行异步任务,应该封装到一个新的promise里面,并返回。

new Promise((resolve,reject)=>{
    resolve(2)
})
.then(
value=>{
    return new Promise(resolve,reject){
        setTimeout(()=>{
            resolve(3)
        },1000)
    }
},
    reason=>{}
)

6、promise异常穿透?

(1) 当使用promise的then链式调用时,可以在最后指定失败的回调

(2) 前面任何操作出了异常,都会传导最后失败的回调中处理

当promise中失败了,而在then中没有指定失败的回调函数,相当于默认的失败回调函数是reason=>{throw reason}

如果前面的then处理了失败回调,那么返回成功。

7、中断promise链?

(1) 当使用promise的then链式调用时,在中间中断,不再调用后面的回调函数

(2) 办法:在回调函数中返回一个pending状态的promise对象

return new Promise(()=>{})//返回一个pending的promise,中断promise链