【JS学习】js中 then、catch、finally
1、 Promise 的状态一经改变就不能改变,也就是说一个Promise实例执行后只有一个状态,要么是resolve, 要么是reject 。
resolve或reject后遇到reject或resolve会忽略该代码不执行。
但是其他代码仍然会执行。
var promise = new Promise((resolve, reject) => { resolve("success1"); console.log('123'); reject("error"); console.log('456'); resolve("success2"); }); promise .then(res => { console.log("then: ", res); }).catch(err => { console.log("catch: ", err); })
运行结果:
123
456
then: success1
2、then 、 catch 、 finally 都会返回一个新的 promise, 所以可以链式调用。
在Promise
中,返回任意一个非 promise
的值都会被包裹成 promise
对象,
例如 return 'hehe'
会被包装为return Promise.resolve('hehe')
。
return 的值只会往下传给 then,无论中间是否有catch 或者 finally。
var promise = new Promise((resolve, reject) => { setTimeout(() => { resolve("success1"); }, 1000) }); promise .then(res => { console.log("then: ", res); return 'bibi'; }).catch(err => { console.log("catch: ", err); return 'err'; }).finally((fin)=> { console.log(fin); console.log('final'); return 'haha'; }).then((res) => { console.log(res); console.log('final-after') }).then((res) => { console.log(res); console.log('final-after2') })
运行结果:
then: success1
undefined
final
bibi
final-after
undefined
final-after2
3、catch 可以捕捉上层错误,但是对下层错误是捕捉不到的。
var promise = new Promise((resolve, reject) => { setTimeout(() => { reject("error"); }, 1000) }); promise .then(res => { console.log("then: ", res); return 'bibi'; }).catch(err => { console.log("catch: ", err); return 'err'; // 这里返回了一个 Promise }).then((res)=> { // 继续执行 console.log('then2', res); return Promise.reject('error2'); }).catch((err) => { //捕捉上层错误,可以隔层捕捉,但是捕捉过的错误不能再捕捉 console.log('catch2', err); })
运行结果:
catch: error
then2 err
catch2 error2
作者:gtea
博客地址:https://www.cnblogs.com/gtea
分类:
JavaScript相关
标签:
JS
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南