当前位置: 首页 > news >正文

JS中async/await功能介绍和使用演示

JS 中 async/await 功能介绍与使用演示

一、功能介绍
  1. 基本概念

    • async:用于声明异步函数,返回一个 Promise 对象。即使函数内没有显式返回 Promise,也会隐式将返回值封装为 Promise.resolve()
    • await:仅能在 async 函数内部使用,用于等待 Promise 对象的解析(resolve)或拒绝(reject)。它使异步代码看起来类似同步代码,提升可读性。
  2. 核心特性

    • 异步流程同步化:通过 await 暂停函数执行,直到 Promise 完成,再继续后续逻辑。
    • 错误传播:若 await 后的 Promise 被拒绝(reject),会抛出错误,需用 try/catch 捕获。
    • 兼容性async/await 是 ES2017 引入的语法糖,底层基于 Promise,兼容现代浏览器和 Node.js。
  3. 使用场景

    • 替代回调函数和 .then() 链式调用,处理异步操作(如 API 请求、文件读写)。
    • 串行或并行执行多个异步任务,优化代码结构。

二、使用演示
  1. 基础示例:顺序执行异步任务

    // 模拟异步请求函数
    function fetchData(url) {return new Promise((resolve) => {setTimeout(() => {resolve(`Data from ${url}`);}, 1000);});
    }// 使用 async/await 顺序执行
    async function fetchSequentially() {try {const data1 = await fetchData('api1');console.log(data1); // Data from api1const data2 = await fetchData('api2');console.log(data2); // Data from api2} catch (error) {console.error('Error:', error);}
    }fetchSequentially();
    
  2. 并发执行异步任务
    使用 Promise.all 并行处理多个请求,减少总耗时:

    async function fetchConcurrently() {try {const [data1, data2] = await Promise.all([fetchData('api1'),fetchData('api2')]);console.log(data1, data2); // 同时输出两个结果} catch (error) {console.error('Error:', error);}
    }fetchConcurrently();
    
  3. 错误处理
    结合 try/catch 捕获异步错误:

    async function fetchWithErrorHandling() {try {const response = await fetch('https://invalid.url');const data = await response.json(); // 如果响应失败,此处会抛错} catch (error) {console.error('Caught error:', error);}
    }fetchWithErrorHandling();
    
  4. 实用场景:模拟延迟执行
    实现休眠函数:

    function delay(ms) {return new Promise((resolve) => setTimeout(resolve, ms));
    }async function delayedTask() {console.log('Task started');await delay(2000); // 暂停2秒console.log('Task completed');
    }delayedTask();
    

三、注意事项
  1. await 的局限性

    • 只能在 async 函数内使用,否则会抛出语法错误。
    • 后面可以是任意表达式(如字符串、数值),非 Promise 会被自动封装为 Promise.resolve()
  2. 错误处理

    • 未捕获的 reject 会导致 async 函数返回的 Promise 变为 reject 状态,需用 try/catch.catch() 处理。
  3. 性能优化

    • 避免过度串行:连续使用 await 会导致异步任务串行执行,降低性能。可改用 Promise.all 并发处理无关依赖的任务。
    • 不要阻塞主线程:长时间同步操作(如循环)中滥用 await 可能阻塞渲染,需谨慎设计异步流程。

四、总结

async/await 是 JavaScript 异步编程的语法糖,本质是基于 Promise,但提供了更简洁、易读的代码风格。它适用于大多数异步场景,尤其适合需要顺序执行或并发控制的场景。使用时需注意错误处理和性能优化,避免陷入同步思维的误区。


文章转载自:
http://peptide.sxnf.com.cn
http://cardiophobia.sxnf.com.cn
http://idioplasmic.sxnf.com.cn
http://uproar.sxnf.com.cn
http://aperitive.sxnf.com.cn
http://psilanthropy.sxnf.com.cn
http://solarize.sxnf.com.cn
http://halve.sxnf.com.cn
http://semaphore.sxnf.com.cn
http://bushel.sxnf.com.cn
http://lmg.sxnf.com.cn
http://garotte.sxnf.com.cn
http://verminicide.sxnf.com.cn
http://crusian.sxnf.com.cn
http://sorefalcon.sxnf.com.cn
http://jules.sxnf.com.cn
http://digitated.sxnf.com.cn
http://purple.sxnf.com.cn
http://unprophetic.sxnf.com.cn
http://tillage.sxnf.com.cn
http://lias.sxnf.com.cn
http://pneumatism.sxnf.com.cn
http://entotic.sxnf.com.cn
http://lila.sxnf.com.cn
http://harris.sxnf.com.cn
http://mallorca.sxnf.com.cn
http://bandsaw.sxnf.com.cn
http://frazzle.sxnf.com.cn
http://halidome.sxnf.com.cn
http://geraniol.sxnf.com.cn
http://www.dtcms.com/a/280341.html

相关文章:

  • 普通字符类型和new String有什么区别
  • 使用JS编写动态表格
  • 【env环境】rtthread5.1.0使用fal组件
  • AI的外挂知识库,RAG检索增强生成技术
  • 【PTA数据结构 | C语言版】将表达式树转换成中缀表达式
  • 数仓面试题
  • 2025最新国产用例管理工具评测:Gitee Test、禅道、蓝凌测试、TestOps 哪家更懂研发协同?
  • docker停止所有容器和删除所有镜像
  • 从一道题目(阿里2014 Crackme_2)开启unidbg还原算法入门(转载)
  • 强化学习书籍
  • vscode 打开c++文件注释乱码
  • 分布式存储之Ceph使用指南--部署篇(未完待续)
  • Claude 背后金主亚马逊亲自下场,重磅发布 AI 编程工具 Kiro 现已开启免费试用
  • 【交叉编译报错】fatal: not a git repository (or any of the parent directories): .git
  • 分布式全局唯一ID生成:雪花算法 vs Redis Increment,怎么选?
  • 内存的基础相关知识,什么是内存,内存管理
  • 死锁问题以及读写锁和自旋锁介绍【Linux操作系统】
  • Spring 中 @Component和@Bean注解的区别
  • 为何说分布式 AI 推理已成为下一代计算方式
  • SpringBoot 2.x→3.0升级实战:Jakarta EE兼容性改造清单
  • kotlin布局交互
  • Kotlin聚合方法
  • Python 操作Excel工作表:添加、删除、移动、隐藏
  • 前端安全指南:防御XSS与CSRF攻击
  • 给 Excel 整列空格文字内容加上前缀:像给文字穿衣服一样简单!
  • Excel制作玫瑰图
  • PostgreSQL FATAL: sorry, too many clients already 连接数爆满的处理办法
  • excel 通过openpyxl表格下载和插入图片
  • 京东平台商品评论接口接入指南与代码实现
  • 国内大模型技术与应用综述