【JavaScript 基础】-- Promise中的then、catch、finally总结
总结:
1、Promise的状态一经改变就不能再改变。
const promise = new Promise((resolve, reject) => {
resolve("success1");
reject("error");
resolve("success2");
});
promise
.then(res => {
console.log("then: ", res);
}).catch(err => {
console.log("catch: ", err);
})
// then:success1
2.、then和catch都会返回一个新的Promise。
3、catch不管被连接到哪里,都能捕获上层未捕捉过的错误。
const promise = new Promise((resolve, reject) => {
reject("error");
resolve("success2");
});
promise
.then(res => {
console.log("then1: ", res);
}).then(res => {
console.log("then2: ", res);
}).catch(err => {
console.log("catch: ", err);
}).then(res => {
console.log("then3: ", res);
})
//"catch: " "error" 验证第三点的总结
//"then3: " undefined 验证第二点总结
4、在Promise中,返回任意一个非 promise 的值都会被包裹成 promise 对象,例如return 2会被包装为return Promise.resolve(2)。
5、Promise 的 .then 或者 .catch 可以被调用多次, 但如果Promise内部的状态一经改变,并且有了一个值,那么后续每次调用.then或者.catch的时候都会直接拿到该值。
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('timer')
resolve('success')
}, 1000)
})
const start = Date.now();
promise.then(res => {
console.log(res, Date.now() - start)
})
promise.then(res => {
console.log(res, Date.now() - start)
})
//'timer'
//'success' 1001
//'success' 1002
// Promise 的 .then 或者 .catch 可以被调用多次,但这里 Promise 构造函数只执行一次。
// 或者说 promise 内部状态一经改变,并且有了一个值,那么后续每次调用 .then 或者 .catch 都会直接拿到该值。
6、.then 或者 .catch 中 return 一个 error 对象并不会抛出错误,所以不会被后续的 .catch 捕获。
Promise.resolve().then(() => {
return new Error('error!!!')
}).then(res => {
console.log("then: ", res)
}).catch(err => {
console.log("catch: ", err)
})
//"then: " "Error: error!!!"
// 这验证了第4点和第6点,返回任意一个非 promise 的值都会被包裹成 promise 对象,
// 因此这里的return new Error('error!!!')也被包裹成了return Promise.resolve(new Error('error!!!'))。
当然如果你抛出一个错误的话,可以用下面的任意一种:
return Promise.reject(new Error('error!!!'));
// or
throw new Error('error!!!')
7、.then 或 .catch 返回的值不能是 promise 本身,否则会造成死循环。
8、.then 或者 .catch 的参数期望是函数,传入非函数则会发生值透传。
Promise.resolve(1)
.then(2)
.then(Promise.resolve(3))
.then(console.log)
// 1
// 第一个then和第二个then中传入的都不是函数,一个是数字类型,一个是对象类型
// 因此发生了透传,将resolve(1) 的值直接传到最后一个then里。
9、.then方法是能接收两个参数的,第一个是处理成功的函数,第二个是处理失败的函数,再某些时候你可以认为catch是.then第二个参数的简便写法。
10、.finally方法也是返回一个Promise,他在Promise结束的时候,无论结果为resolved还是rejected,都会执行里面的回调函数。
①.finally()方法不管Promise对象最后的状态如何都会执行
②.finally()方法的回调函数不接受任何的参数,也就是说你在.finally()函数中是没法知道Promise最终的状态是resolved还是rejected的
③它最终返回的默认会是一个上一次的Promise对象值,不过如果抛出的是一个异常则返回异常的Promise对象。
新一代开源开发者平台 GitCode,通过集成代码托管服务、代码仓库以及可信赖的开源组件库,让开发者可以在云端进行代码托管和开发。旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。
更多推荐



所有评论(0)