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

相关推荐
Hugh-Yu-1301237 分钟前
二元一次方程组求解器c++代码
开发语言·c++·算法
weixin_5206498712 分钟前
C#进阶-特性全知识点总结
开发语言·c#
文祐14 分钟前
C++类之虚函数表及其内存布局
开发语言·c++
Hooray23 分钟前
为了在 Vue 项目里用上想要的 React 组件,我写了这个 skill
前端·ai编程
咸鱼翻身了么25 分钟前
模仿ai数据流 开箱即用
前端
风花雪月_25 分钟前
🔥IntersectionObserver:前端性能优化的“隐形监工”
前端
Bigger25 分钟前
告别 AI 塑料感:我是如何用 frontend-design skill 重塑项目官网的
前端·ai编程·trae
发际线向北25 分钟前
0x02 Android DI 框架解析之Hilt
前端
编程大师哥31 分钟前
C++类和对象
开发语言·c++·算法
M1582276905532 分钟前
工业 CAN 总线无线互联利器|4 路 CAN 转 4G/WiFi 网关 产品介绍
开发语言·php