前端学习

前端学习

@色少1年前

03/27
09:11
前端技能

promise.then 引发的奇思妙想

promise.then?Promise 的成功和失败情况的回调函数

1
2
3
var p1 = new Promise((resolve, reject) => {
resolve('成功!');
});

P1.then().then().then().then() 假设中间一个then 出错了后面的then会执行吗?

写了多年代码的你肯定说被catch掉后面肯定不执行啊!OTL~没catch呢?就是只是问执行不执行?

1
2
3
4
5
6
var p1 = new Promise((resolve, reject) =>{
  resolve("成功!");
});p1
    .then(()=>{console.info(1)})
    .then(()=>{throw new Error("出错了";)})
    .then(()=>{console.info(3)},(e)=>{console.info(e)})

神奇的一幕出现了居然是执行的并且作为下一个then的参数传入。其实then的方法早在mdn上有解析。

问题又来了?神奇的菜鸟问那第二个错了,第三个传入了第二参数,第四个还会执行吗?



真是神奇。并且后面的then居然是返回resolve 真是神奇的一幕。翻查mdn

既然then 是回调函数总会返回和执行这就产生新的问题了?那怎样才能中断呢?

1
2
3
4
5
6
7
var p1 = new Promise((resolve, reject) => {
resolve('成功!');
});p1
.then(()=>{console.info(1)})
.then(()=>{return new Promise((resolve,reject)=>{})})
.then(()=>{console.info(3)},(e)=>{console.info('33')})
.then(()=>{console.info(4)},(e)=>{;console.info(e)})

promise.then 引发的奇思妙想