前言
本文是自己在学习promise中的小总结,可能写的不是很好,但希望对大家有些帮助,参考资料来自B站的up主:https://www.bilibili.com/video/BV1454y1R7vj?p=1
自己在学习中也遇到了个小bug
Uncaught ReferenceError: promise is not defined
我还找了很久,还以为需要导包问题
这里就是P需要大写的。希望能帮到大家。
不过我想没我这么笨的人了吧。
一、promise
1.promise的基本使用
语法
new Promise((resolve,reject)=>{})
- Promise 接受一个函数作为参数
- 在参数函数中接受2个参数
- -resolve (成功的)
- -reject (失败的)
promise实列
具有2个属性
- state:状态
- result: 结果
(1)promise的状态
第一种状态:pending(准备,待解决,进行中)
第二种状态:fulfilled(已完成,成功)
第三种状态:rejected(已拒绝,失败)
(2)promise状态的改变
通过调用resolve()和reject()改变当前promise对象的状态
- resolve():调用函数,使当前promise对象的状态改为fulfilled (成功)
- reject() :调用函数,使当前promise对象的状态改成rejected (失败)
2.promise方法的使用
1.then() 方法
const p =new Promise((resolve,reject)=>{
})
p.then(()=>{
//当promise的状态为fulfilled时执行
console.log('执行成功')
},
()=>{
//当promise的状态为rejected时执行
console.log('执行失败')
})
参数:一个是函数,另一个还是函数
-
当状态为fulfilled时,执行第一个函数(成功函数)
-
当状态为rejected时,执行第二个函数 (失败函数)
-
在then方法的参数函数中,通过形参使用promise对象的结果
-
then()的返回值为依然是一个promise对象,此刻的状态为pending
-
如果promise中的状态不改变,则then不执行
-
在then方法中,通过return将返回值,promise实例改为fulfilled状态
-
在then方法中,出现代码错误,则会将返回的promise实例改为rejiected状态
2.catch() 方法
const p =new Promise((resolve,reject)=>{
//reject()
//console.log(a) 此时a为定义,则报错
throw new Error('出错了')
})
p.catch((reason)=>{
console.log('失败',reason)
})
- 当promise的状态改为rejected时,被执行
- 当promise 执行体中出现代码错误时,被执行
小总结
then方法里面的第二个函数和catch 类似,所以大多都是then.().catch()结合使用
new Promise((resolve,reject)=>{
}).then((value)=>{
//成功时被执行
console.log(value)
}).catch((reason)=>{
//失败时被执行
console.log(reason)
})