讲解Promise任务链之前先看一个例子
new Promise( (resolve, reject) => {
reject();
} ).then(
() => {
console.log('resolve', 1);
},
() => {
console.log('reject', 2);
}
).then(
() => {
console.log('resolve', 3);
},
() => {
console.log('reject', 4);
}
);
猜猜控制台会打印什么东西呢,正确答案是
'reject', 2
'resolve', 3
想知道为什么,继续往下看
Promise Chain
then函数执行后会返回一个新的Promise对象
如果then没有传入处理函数,那么会返回一个继承了上一个处理状态的 Promise 对象
new Promise( (resolve, reject) => {
reject();
} ).then().then(() => {
console.log(1)
},() => {
console.log(2)
})
上面代码会打印2。
如果then传入处理函数,那么默认返回一个 fulfilled/resolved 状态的 Promise 对象
new Promise( (resolve, reject) => {
reject();
} ).then(() => {
console.log(1);
},() => {
console.log(2)
}).then(() => {
console.log(3)
},() => {
console.log(4)
})
上面代码会打印2,3
如果then传入了处理函数,通过处理函数显示的return了一个新的 Promise,那么返回这个显示的 Promise 对象
new Promise( (resolve, reject) => {
reject();
} ).then(() => {
console.log(1);
},() => {
console.log(2);
return new Promise((resolve, reject) => {
reject();
})
}).then(() => {
console.log(3);
},() => {
console.log(4);
})
上面代码会打印2,4。
到这里一开始的问题就清楚了。但是,还会导致一个问题
问题:
不易中途终止后续任务执行
看下面一个例子就知道了
<script type="text/javascript">
new Promise( (resolve, reject) => {
resolve();
} )
.then(() => {
console.log('登录成功')
// 获取权限
return new Promise( (resolve, reject) => {
if (false) { //是否是管理员
resolve();
} else {
reject();
}
} )
},() => {
console.log('登录失败')
})
.then(() => {
console.log('是管理员')
// 获取资源
return new Promise( (resolve, reject) => {
resolve();
// reject();
} )
},() => {
console.log('不是管理员')
})
.then(() => {
console.log('拿到资源')
},() => {
console.log('不能获取资源')
});
</script>
打印结果为
上面当他不是管理员的时候,我们根本就不想让他拿到资源,甚至都不想发这个请求,那怎么办呢?
.catch方法
处理 rejected 的情况,与 then 的第二个参数 onRejected 相同
返回一个 Promise 对象,状态默认为 fulfilled/resolved
可以捕获 catch 之前的 Promise Chain 中的任一错误(如果 Promise Chain 中的 then 没有处理的话)
<script type="text/javascript">
new Promise( (resolve, reject) => {
resolve();
} )
.then(() => {
return new Promise( (resolve, reject) => {
reject('登录失败');
} )
})
.then(() => {
console.log('是管理员')
})
.then(() => {
console.log('拿到资源')
}).catch(err => {
console.log(err);
}).then(() => {
console.log('catch以后')
});
</script>