当前位置:网站首页>Promise (I)

Promise (I)

2022-04-23 16:59:00 Endless cake

Promise Three states of

1.pending
2.resolved
3.rejected

Three state relationships
pending -> resolved ( Can convert )
pending -> rejected ( Can convert )

    <script>
        const p1 = new Promise((resolve, reject) => { // establish promise
        })
        console.log(p1)
            // pending=>resolved
        const p2 = new Promise((resolve, reject) => { // establish promise2
            resolve()
        })
        console.log(p2)
            // pending=>reject
        const p3 = new Promise((resolve, reject) => { // establish promise3
            reject()
        })
        console.log(p3)
    </script>

Promise Different state performance

//pending In state promise Not trigger then  and catch 
const p1 = new Promise((resolve, reject) => { // establish promise
   })
 console.log(p1)
 p1.then(()=>{
console.log('p1 then')
}).catch(()=>{
console.log('p1 catch')
})
//resolve In state promise Will trigger then The callback function inside 
const p2 = Priomise.resolve() // Abbreviation 
 p2.then(()=>{
console.log('p2 then')
}).catch(()=>{
console.log('p2 catch')
})

//reject In state promise Will trigger catch  The callback function inside 
const p3 = Promise reject()
 p3.then(()=>{
console.log('p3 then')
}).catch(()=>{
console.log('p3 catch')
})

then、catch Yes Promise The effect of state

const p1 = Promise.resolve()
console.log(p1)
//p1.then There is no exception thrown in the callback function of , therefore , Will return a resolve
const res = p1.then(()=>{
console.log('success')
})

//p1.then An exception is thrown in the callback function of , therefore , Will return a reject
const res = p1.then(()=>{
 throw new Error('error')// Here I throw an exception 
})


//p1.catch There is no exception thrown in the callback function of , therefore , Will return a resolve
const res = p1.catch(()=>{
console.log('success')
})

//p1.catch An exception is thrown in the callback function of , therefore , Will return a reject
const res = p1.catch(()=>{
 throw new Error('error')// Here I throw an exception 
})

summary : No matter what then || catch Did you throw an exception ,p.then perhaps p.catch Will return to one resolve State of Promise. If an exception is thrown ,p.then perhaps p.catch Will return to reject State of Promise.

版权声明
本文为[Endless cake]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230554519804.html