1、创建promise时的代码是直接执行的
new Promise(res => {
console.log(1)
})
console.log(2)
输出 1 2
2、promise内的东西不会反应到外层,也就是不会被外面到try catch捕获。
new Promise(res => {
throw new Error('asd')
})
console.log(1)
比如下面还是能够输出1
new Promise(res => {
throw new Error('asd')
})
console.log(1)
下面并不能catch到错误
try{
new Promise(res => {
throw new Error('asd')
})
}catch(e){
console.log(e)
}
try{
new Promise(res => {
res(1)
}).then(val=>{
throw new Error('asd')
})
}catch(e){
console.log(e)
}
3、必须用自带到catch方法才能捕获错误,并且promise里和then里面的都能catch到。如下
new Promise(res => {
res(1)
}).then(val=>{
throw new Error('asd')
}).catch(e=>{
console.log(e)//能抓到
})
new Promise(res => {
throw new Error('asd')
}).catch(e=>{
console.log(e)//也能抓到
})
4、状态只能改变一次,且改变状态后的error不能获取
new Promise((res, rej) => {
res(1)
rej(2)
})
.then(val => {
console.log(val)
})
.catch(e => {
console.log(e)
})
new Promise((res, rej) => {
res(1)
throw Error('2')
})
.then(val => {
console.log(val)
})
.catch(e => {
console.log(e)
})
都打印出1,
promise.all()
传入多个promise,如果传入的不是promise对象,则promise.resolve(这个值),都完成才更新状态,返回一个数组
如果有失败的,直接更新为rejected状态
参数p如果有catch
,all的catch
不能捕捉到error
promise.race()
哪个改变状态,就用哪个的状态值。
promise.allSettled()
不管rejected还是resolve,全改变了才改变状态,状态都是resolve。
promise.any()
只要有一个成功,就成功。三个全失败才失败。
promise.resolve()
返回一个promise对象,如果传一个promise对象,则原封不动返回。
promise.reject()
返回一个reject状态的对象。