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

前端学习手册-JavaScript函数与回调(十一)

一、函数的定义

function hello() {console.log("你好!");
}
hello();

二、带参数和返回值

function add(x, y) {return x + y;let result = add(1, 2);
console.log(result); // 输出3

三、箭头函数(ES6新语法)

const multiply = (a, b) => a * b;
console.log(multiply(2, 3)); // 6

四、函数表达式

const add = function(x, y) {return x + y;
};
console.log(add(1, 2));//输出3

五、匿名函数(没有名字的函数)

setTimeout(function() {console.log('延迟1秒输出');
}, 1000);

六、回调函数

回调函数是作为参数传递给另一个函数的函数,在特定事件或条件发生时被调用。

回调函数本质上是一个函数,作为另一个函数的参数。

1.使用命名函数作为回调

2.使用匿名函数作为回调

3.使用箭头函数作为回调(ES6+)

// 形式1:使用命名函数作为回调
function greeting(name) {return `Hello, ${name}!`;
}function processUserInput(input, callback) {const formattedInput = input.trim();return callback(formattedInput);
}
// 将greeting函数作为回调传递
const result1 = processUserInput('  World  ', greeting);
console.log('命名函数作为回调的结果:', result1);// 形式2:使用匿名函数作为回调
const result2 = processUserInput('JavaScript', function(name) {return `Welcome to ${name}!`;
});
console.log('匿名函数作为回调的结果:', result2);// 形式3:使用箭头函数作为回调(ES6+)
const result3 = processUserInput('ES6', (name) => {return `Learning ${name} arrow functions!`;
});
console.log('箭头函数作为回调的结果:', result3);

常见使用场景:

1. 异步API调用(如AJAX请求、文件读写等)

2. 事件处理(如点击事件、键盘事件等)

3. 数组的高阶函数(如forEach、map、filter等)

4. 定时器函数(如setTimeout、setInterval等)

下面是一段嵌套回调的代码示例:

// 嵌套回调与回调地狱
// 模拟异步操作的函数
function fetchUserData(userId, callback) {setTimeout(() => {console.log(`获取用户${userId}数据`);callback({ id: userId, name: `User${userId}` });}, 200);
}
function fetchUserPosts(userData, callback) {setTimeout(() => {console.log(`获取用户${userData.name}的帖子`);callback([{ id: 1, title: `Post by ${userData.name}` },{ id: 2, title: `Another post by ${userData.name}` }]);}, 200);
}
function fetchPostComments(posts, callback) {setTimeout(() => {console.log(`获取帖子的评论`);callback([{ id: 101, postId: 1, content: 'Great post!' },{ id: 102, postId: 1, content: 'Thanks for sharing' }]);}, 200);
}
// 回调地狱示例(多层嵌套的回调函数)
console.log('回调地狱示例开始:');
fetchUserData(1, (userData) => {fetchUserPosts(userData, (posts) => {fetchPostComments(posts, (comments) => {console.log('所有异步操作完成!');console.log('用户:', userData);console.log('帖子:', posts);console.log('评论:', comments);console.log('注意:这种多层嵌套的结构就是回调地狱,代码可读性很差');});});
});

多层嵌套会导致回调地狱,应尽量避免。

回调地狱问题

多层嵌套导致代码可读性差

思考:那怎么解决回调地狱问题呢?使代码更优雅可读性更强?

http://www.dtcms.com/a/395733.html

相关文章:

  • Unity小游戏接入抖音敏感词检测
  • 【2025最新】01 Spring Boot 第一个小程序 for VS Code - 通过 Spring Initializr 网站创建
  • 算法面试(3)------YOLO 的核心思想是什么?YOLOv1 到 v8 的演进路线?
  • docker 部署gitlib
  • SpringBoot3.5.5版本大坑
  • Lightroom Classic 2025专业级数字照片管理与后期处理全解析
  • 交叉编译工具链
  • 前端构建工具有哪些?常用前端构建工具推荐、前端构建工具对比与最佳实践
  • 【RocketMQ入门到精通 | 4】工作原理:indexFile索引文件
  • PPIO首发上线DeepSeek-V3.1-Terminus
  • 《嵌入式驱动(一):系统移植》
  • C语言(长期更新)第22讲:文件操作(一)
  • 财务管控——解读79页集团财务业务管控方法及信息化应用案例【附全文阅读】
  • 火语言RPA:解锁开发者工作流的“自动化密码”
  • 用户行为数据可视化
  • jdbc-数据更新与删除
  • 【GitLab】GitLab-CI(shell方式)入门配置
  • Python入门 | 三个if语句程序作业和基础语法笔记
  • BeanPropertyRowMapper
  • 深入解析Java中String的不可变性
  • windows-安装kafka并启动
  • linux 驱动私有数据
  • 信息系统监理师软考备考指南:组织协调与沟通管理专题精讲
  • 【开题答辩全过程】以 JAVA农产品销售系统为例,包含答辩的问题和答案
  • Python 网络爬虫生态全景综述
  • MCP— Model Context Protocol(模型上下文协议)
  • 解决ubuntu无法连接上security.ubuntu.com:80 (185.125.190.81)的问题
  • SHAP分析 | MATLAB实现XGBoost极限梯度提升树多输入单输出回归预测+SHAP可解释分析分析(预测新数据,多指标评价)
  • 磁共振成像原理(理论)11:梯度回波 (Gradient Echoes)
  • odoo18全局菜单搜索