简单总结-如何理解Promise

简单总结-如何理解Promise

第一点:Promise 构造函数创建完就会首先执行,是同步执行的。而.then是异步执行的执行

const pro = new Promise((resolve,reject)=>{
          console.log(1);
          resolve();
          console.log(2)
})
pro.then(()=>{
console.log(3)
})
//1
//2
//3
const pro= new Promise((resolve,reject)=>{
          console.log(1);
          //resolve();
          console.log(2);
          reject()
})
pro.then(()=>{
          console.log(3)
},()=>{ console.log(4)})
//1
//2
//4
注意:必须调用resolve或者reject 方法才会执行.then //resolve和reject都是在同级其他执行完才会执行

第二点:promise 第一次执行完,return的返回值相当于下一次.then调用传入的参数.promise链式调用,

const pro = Promise.resolve(1);
pro.then((res)=>{
          console.log(res);
          return 2
}).then((res)=>{
          console.log(res);
return 3
}).then((res)=>{
          console.log(res);
          return 4
})
//1
//2
//3

第三点:promise 内部状态一经改变,并且有了一个值,那么后续每次调用 .then 或者 .catch 都会直接拿到该值。即promise 的 .then 或者 .catch 可以被调用多次,但这里 Promise 构造函数只执行一次。

const pro = new Promise((resolve,reject)=>{
setTimeout(()=>{
          console.log(1);
          resolve(‘sucess’);
},1000)
});
let startDate = Date.now();
pro.then((res)=>{
          console.log(res , Date.now() - startDate)
})
pro.then((res)=>{
          console.log(res , Date.now())
})
//1
// sucess 1005
//sucess 1560776673201
注意:状态相同,后面时间不同

第四点:注意return 与 throw的区别

Promise.resolve()
.then(() => {
          return new Error(‘报错’)
})
.then((res) => {
          console.log('then: ', res)
})
.catch((err) => {
          console.log('catch: ', err)
})

//then: Error: return报错 直接return 返回错误信息

Promise.resolve()
.then(() => {
          throw new Error(‘报错’)
})
.then((res) => {
          console.log('then: ', res)
})
.catch((err) => {
          console.log('catch: ', err)
})

//catch: Error: return报错 throw执行catch的报错信息

第五点:.then 或 .catch 返回的值不能是 promise 本身,否则会造成死循环

const pro = Promise.resolve()
.then(() => {
          return pro
})
pro.catch(console.error)

//TypeError: Chaining cycle detected for promise # 报错

第六点 .then 或者 .catch 的参数期望是函数,传入非函数则会发生值穿透。

Promise.resolve(1)
          .then(2)
          .then(Promise.resolve(3))
          .then(4)
//1
注:每次调用.then 就相当于使用上一次的返回值,只有函数才能有return 返回

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值