当前位置:网站首页>Promise(一)
Promise(一)
2022-04-23 05:56:00 【画不完的饼】
Promise的三种状态
1.pending
2.resolved
3.rejected
三种状态关系
pending -> resolved (可以转换)
pending -> rejected (可以转换)
<script>
const p1 = new Promise((resolve, reject) => { //创建promise
})
console.log(p1)
// pending=>resolved
const p2 = new Promise((resolve, reject) => { //创建promise2
resolve()
})
console.log(p2)
// pending=>reject
const p3 = new Promise((resolve, reject) => { //创建promise3
reject()
})
console.log(p3)
</script>
Promise不同状态表现
//pending状态下的promise不会触发then 和catch
const p1 = new Promise((resolve, reject) => { //创建promise
})
console.log(p1)
p1.then(()=>{
console.log('p1 then')
}).catch(()=>{
console.log('p1 catch')
})
//resolve状态下的promise会触发then里面的回调函数
const p2 = Priomise.resolve() //简写
p2.then(()=>{
console.log('p2 then')
}).catch(()=>{
console.log('p2 catch')
})
//reject状态下的promise会触发catch 里面的回调函数
const p3 = Promise reject()
p3.then(()=>{
console.log('p3 then')
}).catch(()=>{
console.log('p3 catch')
})
then、catch对Promise状态的影响
const p1 = Promise.resolve()
console.log(p1)
//p1.then的回调函数里面没有抛出异常,所以,会返回一个resolve
const res = p1.then(()=>{
console.log('success')
})
//p1.then的回调函数里面抛出异常,所以,会返回一个reject
const res = p1.then(()=>{
throw new Error('error')//这里我抛出一个异常
})
//p1.catch的回调函数里面没有抛出异常,所以,会返回一个resolve
const res = p1.catch(()=>{
console.log('success')
})
//p1.catch的回调函数里面抛出异常,所以,会返回一个reject
const res = p1.catch(()=>{
throw new Error('error')//这里我抛出一个异常
})
总结:无论then || catch 有没有抛出异常,p.then或者p.catch都会返回一个resolve状态的Promise。如果抛出异常,p.then或者p.catch都会返回reject状态的Promise。
版权声明
本文为[画不完的饼]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_39162041/article/details/124192644
边栏推荐
猜你喜欢
Informatics one book pass - small ball
el-table添加序号
Makefile foundation, common functions and general makefile
freeCodeCamp----time_calculator练习
Analysis of fixed point PID code of FOC motor Library
若依如何input改成文本
1-4 NodeJS的安装之配置可执行脚本
深入理解控制反转和依赖注入
VHDL finite state machine (FSM) code example
.Net Core 下使用 Quartz —— 【1】快速开始
随机推荐
C# Task.Delay和Thread.Sleep的区别
查漏补缺(九)---程序篇
使用jsonwebtoken生成访问密钥
FOC single resistance sampling position loop control servo motor
C# Dapper 基本使用 增删改查事务等
el-table添加序号
赛氪-zeal
NodeJS 模块之间的使用
写一个正则
.Net Core 下使用 Quartz —— 【5】作业和触发器之触发器的通用属性和优先级
Vs can be compiled, but there will be a red underline to indicate the problem of undefined identifiers
Introduction and application of WMI Technology
Redux概述
js根据名字将数组对象中名字相同的项组成一个相同的数组
Devexpress Gridview 添加全选列
ASP.NET CORE在类库项目中读取配置文件
Declared as a global variable
ASP.NET CORE 依赖注入服务生命周期
记第一次使用阿里字体图标库
服务器常见错误代码 总结