如何阻止promse链式调用的向下执行

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_43316300/article/details/84789103

promise链式的使用和注意细节

promise.js
function test(){
   return new Promise((resolve,reject)=>{
          resolve('this is test')
   },1000);
})
function test2(){
   return new Promise((resolve,reject)=>{
       resolve('this is test2')
   },1000);
}

test()
.then((data)=>{
   console.log('1')
   console.log(data)
   return test2()
})
.then((data)=>{
   console.log('2')
   console.log(data)
//   return false    //无效
   throw new Error('err')   //中止下面then的继续执行
})
.then((data)=>{
   console.log('3')
   console.log(data)
})
.then((data)=>{
   console.log('4')
   console.log(data)
})
.catch((err)=>{
   console.log('err')
   console.log(err)
})

执行结果

  1. promse 对象可以无限写 ;
  2. 在promse链式 return 是无效的 ;
  3. return 是不会中止执行的 ;

中止执行可以通过 throw 来终止链式的执行 直接跳到chatch (出错就会终止)
错误的处理 和返回 需要把它放在chatch
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43316300/article/details/84789103