一丶什么是Promise
Promise 是一个可以用来存储数据的对象,Promise 存储数据的方式比较特殊,这种方式可以用来存储异步调用的数据,它可以帮助我们解决 异步 中回调函数的问题。
二丶怎样创建Promise
创建Promise时,构造函数中需要一个函数作为参数,Promise 构造函数的回调函数,它会在创建 Promise 时调用,调用时会有两个参数传递进去。
const promise = new Promise((reslove,reject)=>{
reslove('哈哈')
})
resolve和reject是两个函数,通过这两个函数可以向 Promise 中存储数据
resolve在执行正常时存储数据, reject 在执行错误时存储数据
三丶怎样从Promise中读取数据
可以通过 Promise 的实例方法 then 来读取 Promise 中存储的数据
then 需要两个回调函数作为参数,回调函数用来获取 Promise 中的数据,通过 resolve 存储的数据,会调用第一个函数返回;通过 reject 存储的数据或出现异常时,会调用第一个函数返回。
promise.then((result)=>{
console.log('Promise中的数据',result);
},(reason)=>{
console.log(reason);
})
他还有两个方法,分别为 catch() 和 finally():
①.catch()用法和then类似,但是只需要一个回调函数作为参数,它只会在Promise被拒绝时才调用。
②.finally()通常用来编写一些无论成功与否,都要执行的代码
四丶Promise中维护了两个隐藏的属性
1. PromiseResult :
用来存储数据
2.PromiseState :
用来记录Promise的状态(三种状态):
①。pendging(进行中)
②。fulfilled(完成) 通过reslove存储数据时
③。rejected(拒绝) 出错了或者通过reject存储数据时
注意:state只能修改一次,修改以后永远不会在变。