Promise构造函数
内置属性 :
PromiseResult(结果值)
PromiseState(状态):pending(初始状态)/fufilled/rejected
PromiseState的状态有且只有两种改变形式:pending>>fufilled ,pending>>rejected
var p = new Promise((resolve,reject)=>{
resolve('ok') <!-- 状态只能改变一次-->
reject('error') <!-- 无效 -->
})
resolve('ok') >> PromiseState:fufilled PromiseResult: ok
reject('error') >> PromiseState:rejected PromiseResult: error
throw 'error' >> PromiseState:rejected PromiseResult: error
new Promise
01.返回值为一个Promise对象
02.有三种形式可以改变PromiseState的状态: resolve、reject、throw
内置方法 :then() catch()
then ()
const res = p.then(value=>{
console.log(value)
},reason=>{
console.log(reason)
})
(返回值)
console.log(res) >> PromiseState:fufilled PromiseResult: undefined
原因: then方法没有return返回一个值
无return >> PromiseState:fufilled PromiseResult: undefined
有return a (a:非promise) >> PromiseState:fufilled PromiseResult: a
有return a (a:promise) >> PromiseState:*(具体以a返回的状态决定) PromiseResult: *(具体以a返回的结果值决定)
value/reason 为PromiseResult的值
catch ()
const res = p.catch(reason=>{
console.log(reason)
})