Promise基础用法

2022-11-20 14:49:42

Promise

promise对象代表一个异步操作,有三种状态

  • pending 代表初始状态 不是成功或是失败状态
  • fulfilled 意味着操作成功完成
  • rejected 意味操作失败

优点

  • 避免回调地狱问题
  • 提供统一接口,使得异步控制更加容易

缺点

  • 无法取消Promise
  • 只有设置回调函数Promise内部抛出的错误才能反应到外部
  • pending状态时,无法得知当前状态是刚刚开始还是即将结束

基础用法

<script>functiondemo(){returnnewPromise((resolve,reject)=>{setTimeout(()=>{//pending 状态一经改变不会再变let num=Math.round(Math.random()*100);if(num%2==0){//从pending状态变为fulfilled状态resolve("num是偶数"+num)}else{//从pending状态变为rejected状态reject(newError("num是奇数"+num));}},500)})}
		console.log('运行中……')demo().then((res)=>{
			console.log(res)}).catch((err)=>{
			console.log(err)})</script>
  • 作者:吃不胖的小胖子。
  • 原文链接:https://blog.csdn.net/zhangzhixiong_/article/details/124962043
    更新时间:2022-11-20 14:49:42