当前位置:网站首页>初步认识Promse
初步认识Promse
2022-04-23 05:56:00 【画不完的饼】
Promse是什么?
- 抽象表达:Promise是JS中进行异步编程的新的解决方案(以前都用callback回调函数)
- 具体表达:
(1)从语法上来说:Promise是一个构造函数
(2)从功能上来说:Promise对象用来封装一个异步操作并可以获取其结果
为什么要用Promise?
一 .
- 指定回调函数的方式更加灵活
- 必须在启动异步任务前指定
- Promise:启动异步任务 => 返回Promise对象 =>给Promise绑定回调函数,甚至可以在异步任务完结之后,在回调请求结果
二.
1.Promise支持链式调用,可以解决回调地狱问题
什么是回调地狱?
多个异步请求串联调用,并回调,就会出现回调地狱
回调函数嵌套调用的时候,不便于阅读,也不便于异常处理
Promise链式调用解决回调地狱代码如下:
//不是嵌套关系的调用,所以不会产生回调地狱的问题
fn1().then((result)=>{
return fn1(result)
})
.then((result2)=>{
return fn2(result2)
})
.then((result3)=>{
console.log('success')
}).catch(()=>{//异常传投。任何一个出问题都会传到catch
console.log('error')
})
最完美的回调地狱解决方案其实是 async/await
纯粹的同步编码方式
async function request(){
try{
const result = await fn1()
const result2 = await fn2()
const result3 = await fn3 ()
console.log('最终结果:'+result3)
}catch(error){
console.log('error')
}
}
版权声明
本文为[画不完的饼]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_39162041/article/details/124296110
边栏推荐
猜你喜欢
随机推荐
Promise(三)
1-4 NodeJS的安装之配置可执行脚本
写一个正则
小米摄像头异常解决
Informatics one book pass - small ball
v-for下定时给图片添加动画
浏览器中堆栈内存的底层处理
.Net Core 下使用 Quartz —— 【1】快速开始
Detailed explanation and application of PN junction and diode principle
查漏补缺(八)
New type of dark energy could solve Universe expansion mystery
Router对象、Route对象、声明式导航、编程式导航
el-form表单多重循环校验
Parse PSD files and map them into components
Set与Map
Palindromic Primes
1-2 NodeJS的特点
WebSocket(基础)
Assembler 32-bit unsigned addition calculator
excel快速自动填充空白单元格上一行的内容








