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

相关推荐
hadeas21 小时前
Spring 技术栈学习文档(面向前端开发者)
前端
狗头大军之江苏分军21 小时前
Python 协程进化史:从 yield 到 async/await 的底层实现
前端·后端
jay神21 小时前
基于YOLOv8的交通标志识别Web系统
前端·人工智能·深度学习·yolo·机器学习·毕业设计
CAD老兵21 小时前
一张 HTML 走天下:CAD-Viewer 首创的「离线 CAD 看图」
前端·javascript·github
程序员榴莲21 小时前
Python 中的 @property:像访问属性一样调用方法
开发语言·前端·python
yingyima21 小时前
Linux定时任务:crontab vs systemd timer,到底谁更适合你的业务?
前端
sycmancia1 天前
Qt——拖放事件深度剖析
开发语言·qt
坐吃山猪1 天前
【Nanobot】README09_LEVEL4 添加新聊天渠道
开发语言·网络·python·源码·nanobot
shehuiyuelaiyuehao1 天前
算法27,二维前缀和
开发语言·python·算法
IpdataCloud1 天前
企业安全运营中,如何用IP风险识别工具快速发现异常终端?操作指南
开发语言·php