promise中链式调用then的问题

本文探讨Promise在处理异步操作时的链式调用特性,通过测试代码和总结图示,揭示了Promise.then执行的顺序和原理。
摘要由CSDN通过智能技术生成

promise是一个很好的解决异步调用的方法,其链式调用也是一个很好的方式,这里探究一下其调用过程

主要问题
Promise.resolve()
.then(res => {
   
  return new Promise()  
})

Promise.resolve()
.then(res => {
   
  new Promise()  
})

// 上下两种Promise的方式中, 是否会进行下去,以及新产生的promise是否会被传递下去,或者说有什么区别

测试代码

每一句打印后面都输出了时间戳,是为了更好描述运行顺序
测试代码直接贴在下方,可以拿到浏览器中进行测试查看

;(function () {
   
  // fn1()
  // fn1_1()
  // fn2()
  // fn3()
  // fn4()
  // fn5()
  // fn6()
  // fn7()
  // fn8()
  // fn9()
})()

function fn1 () {
   
  console.log('start', new Date().getTime())
  new Promise(resolve => {
   
    console.log('11111', new Date().getTime())
    
  }).then(res => {
   
    console.log('22222', new Date().getTime())
    
  }).then(res => {
   
    console.log('33333', new Date().getTime())

  })
  console.log('end', new Date().getTime())
  
  /*
  start 1560165694777
  11111 1560165694787
  end 1560165694790
  */
}

function fn1_1 () {
    
  console.log('start', new Date().getTime())
  new Promise(resolve => {
   
    console.log('11111', new Date().getTime())
    resolve()
    console.log('11111-1111', new Date().getTime())
  }).then(res => {
   
    console.log('22222', new Date().getTime())
    
  }).then(res => {
   
    console.log('33333', new Date().getTime())

  })
  console.log('end', new Date().getTime())
  
  /*
  start 1560166834093
  11111 1560166834106
  11111-1111 1560166834108
  end 1560166834110
  22222 1560166834115
  33333 1560166834119
  */
}

/*
通过前 fn1, fn1_1 两个小例子可知,最开始的new Promise可能对我们进行干扰,
出现这种状况的原因是,申明 new Promise的时候此时异步还未开始,所以我们
直接按照接下来的方式进行测试
*/

function fn2 () {
   
  console.log('start', new Date().getTime(
  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值