Promise链式调用
- then 和 catch 都会返回一个新的Promise
- then方法接收两个参数(onfulfilled, onrejected)
- 两个参数分别处理上一个Promise的resolve状态和reject状态
- 处理结束后可以返回值或Promise,此时then方法返回的Promise处于resolve状态
- 处理过程中可以抛出错误,此时then方法返回的Promise处于reject状态
- catch方法接收一个参数(onrejected)
- 这个参数只可以处理上一个Promise的reject状态
- 处理结束后可以返回值或Promise,此时catch方法返回的Promise处于resolve状态
- 处理过程中可以抛出错误,此时catch方法返回的Promise处于reject状态
function test(p) {
return new Promise((resolve, reject) => {
if (p) resolve(p);
reject("error-undefined");
});
}
test("【test】: res")
.then((res) => {
console.log(res, "--then1");
return new Promise((resolve, reject) => {
reject("【then1】: error");
});
})
.catch((err) => {
console.log(err, "--catch1");
return "【catch】: res";
})
.then((res) => {
console.log(res, "--then2");
throw new Error("【then2】: error");
})
.catch((err) => {
console.log(err.message, "--catch2");
});
结果
【test】: res --then1
【then1】: error --catch1
【catch】: res --then2
【then2】: error --catch2
如有不对,欢迎指正!