ecmascript中Promise和async/await的区别

在学习前端过程中一直没弄明白这个,后面问了AI后才明白。

特性 Promise async/await
语法 链式调用 .then().catch() 类似同步代码的写法
错误处理 使用 .catch()或第二个参数 使用 try-catch
可读性 回调地狱风险 代码更清晰易读
调试 调试相对复杂 调试更方便,有同步代码的感觉
javascript 复制代码
// Promise 方式
function getUserData(userId) {
    return fetchUser(userId)
        .then(user => fetchProfile(user.id))
        .then(profile => fetchPosts(profile.userId))
        .then(posts => {
            console.log('所有数据获取完成');
            return posts;
        })
        .catch(error => console.error('出错:', error));
}

// async/await 方式
async function getUserDataAsync(userId) {
    try {
        const user = await fetchUser(userId);
        const profile = await fetchProfile(user.id);
        const posts = await fetchPosts(profile.userId);
        console.log('所有数据获取完成');
        return posts;
    } catch (error) {
        console.error('出错:', error);
    }
}

重要关系

  • async 函数总是返回一个 Promise

  • await 只能在 async 函数中使用

  • await 后面可以跟任何 thenable 对象(主要是 Promise)

javascript 复制代码
async function example() {
    return 'hello'; // 自动包装成 Promise
}

// 等价于
function example() {
    return Promise.resolve('hello');
}

总结

  • Promise​ 是处理异步操作的底层机制

  • async/await​ 是基于 Promise 的语法糖,让代码更易读写

  • 两者可以混合使用,根据场景选择最合适的写法

  • 现代 JavaScript 开发中,推荐使用 async/await 来提高代码可读性

https://blog.csdn.net/zlpzlpzyd/article/details/148035513

相关推荐
多多鼠16 分钟前
System Prompt 的“版本漂移”问题:从变更管理到 A/B 测试体系
开发语言·网络·人工智能·python·langchain
DyLatte17 分钟前
AI 给了我 8 个优化方案,全都是对的,但没有一个有用
前端·后端·程序员
WiChP23 分钟前
【V0.1B16】从零开始的2D游戏引擎开发之路
开发语言·算法·游戏引擎
the局外人26 分钟前
一座不够大的城市,装下了我毕业后的成长
前端·程序员·求职
涛涛ing1 小时前
周下载量1.1亿的Tailwind,为什么养不活自己?
前端
变与不变8061 小时前
JS事件机制精讲
前端·javascript
装备研究社1 小时前
Promise 的五个状态,90% 的人只说对了三个
前端
孙启超1 小时前
【AI开发之Rust】第 8 课:泛型、trait 与 trait 对象
开发语言·后端·rust
小聪7081 小时前
elpis-core 抽离 npm 包过程的难点和卡点
前端·架构
2501_933670792 小时前
经营财务岗技能栈拆解:Excel、SQL、BI、预算分析怎么准备
开发语言