在蓝桥杯 Web 应用开发赛项中,异步编程是必考的核心内容。无论是处理用户交互、获取后端数据,还是动态更新页面,都离不开 箭头函数 、Promise 和 Fetch API 的熟练运用。本文将系统梳理这三个知识点,并通过代码实例与表格总结,帮助你在备赛过程中牢牢掌握这些关键技能。
一、箭头函数(Arrow Function)
箭头函数是 ES6 引入的一种简洁的函数写法,它不仅让代码更短,还改变了 this 的指向规则,在回调函数、事件监听等场景中尤为常用。
1.1 基本语法
| 形式 | 语法 | 示例 |
|---|---|---|
| 无参数 | () => { ... } |
() => console.log('hello') |
| 一个参数 | x => { ... } 或 (x) => { ... } |
x => x * 2 |
| 多个参数 | (x, y) => { ... } |
(a, b) => a + b |
| 函数体单行,隐式返回 | (x, y) => x + y |
省略 {} 和 return,直接返回值 |
| 函数体多行 | (x, y) => { let sum = x + y; return sum; } |
必须写 {} 和 return |
1.2 this 指向
箭头函数没有自己的 this ,它内部的 this 定义时所在上下文的 this 值,而非调用时决定。这一点与普通函数截然不同。
// 普通函数:this 指向调用者
div.onclick = function() {
console.log(this); // <div class="div1">...</div>
};
// 箭头函数:this 指向外层作用域(window)
div.onclick = () => {
console.log(this); // window
};
1.3 应用场景
-
数组方法(
map、filter、forEach)的回调 -
事件监听中需要保留外层
this -
Promise 链式调用中简化回调
1.4 表格总结:箭头函数核心特性
| 特性 | 说明 | 代码示例 |
|---|---|---|
| 语法简洁 | 根据参数个数和函数体行数可省略括号、花括号、return | let add = (a,b) => a+b; |
| 无自己的 this | this 继承自外层作用域 | setTimeout(() => { console.log(this); }, 100); |
| 不能用作构造函数 | 不能使用 new 调用 |
new (() => {}) 会报错 |
没有 arguments 对象 |
可用剩余参数代替 | (...args) => console.log(args) |
| 不能作为生成器函数 | 不支持 yield |
- |
二、Promise 对象
Promise 是 ES6 提出的异步编程解决方案,它代表一个异步操作的最终完成(或失败)及其结果值,解决了"回调地狱"问题。
2.1 Promise 的三种状态
-
pending(进行中):初始状态,既未完成也未失败。
-
fulfilled(已成功) :操作成功,调用
resolve。 -
rejected(已失败) :操作失败,调用
reject。
2.2 创建 Promise
const promise = new Promise((resolve, reject) => {
// 异步操作
if (/* 成功条件 */) {
resolve('成功的数据');
} else {
reject('失败的原因');
}
});
2.3 链式调用
then() 方法接收两个回调:第一个处理成功,第二个处理失败(可选)。catch() 专门处理失败。finally() 无论成败都会执行。
fetchData()
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error))
.finally(() => console.log('请求结束'));
2.4 解决回调地狱
传统异步嵌套:
ajax1(() => {
ajax2(() => {
ajax3(() => {
// 最终逻辑
});
});
});
用 Promise 改写:
ajax1()
.then(() => ajax2())
.then(() => ajax3())
.then(() => {
// 最终逻辑
})
.catch(err => console.error(err));
2.5 表格总结:Promise 核心 API
| 方法 | 作用 | 示例 |
|---|---|---|
new Promise(executor) |
创建一个 Promise 实例 | new Promise((resolve,reject)=>{...}) |
promise.then(onFulfilled, onRejected) |
注册成功和失败回调,返回新 Promise | promise.then(data=>{}, err=>{}) |
promise.catch(onRejected) |
仅处理失败,相当于 then(null, onRejected) |
promise.catch(err=>{}) |
promise.finally(onFinally) |
无论成败都执行,不改变结果 | promise.finally(()=>{}) |
Promise.resolve(value) |
返回一个已成功的 Promise | Promise.resolve(42) |
Promise.reject(reason) |
返回一个已失败的 Promise | Promise.reject('error') |
Promise.all(iterable) |
所有 Promise 成功才成功,返回结果数组 | Promise.all([p1, p2]) |
Promise.race(iterable) |
第一个结束的 Promise 决定结果 | Promise.race([p1, p2]) |
三、Fetch API
Fetch API 提供了全局 fetch() 方法,用于发起网络请求,它返回一个 Promise,因此天然支持异步流程控制,比传统的 XMLHttpRequest 更简洁、强大。
3.1 基本 GET 请求
fetch('./carList.json') // 返回 Promise<Response>
.then(response => {
if (response.ok) { // 响应状态码 200-299
return response.json(); // 解析 JSON,返回 Promise
} else {
throw new Error(`HTTP error! status: ${response.status}`);
}
})
.then(data => {
console.log(data); // 处理解析后的数据
})
.catch(error => {
console.error('请求失败:', error);
});
3.2 响应对象常用方法
| 方法 | 作用 | 返回值类型 |
|---|---|---|
response.json() |
将响应体解析为 JSON | Promise |
response.text() |
将响应体解析为文本 | Promise |
response.blob() |
将响应体解析为 Blob 对象 | Promise |
response.formData() |
将响应体解析为 FormData | Promise |
response.arrayBuffer() |
将响应体解析为 ArrayBuffer | Promise |
3.3 请求配置(POST 等)
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name: '张三', age: 20 }),
})
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.error(err));
3.4 错误处理
-
网络故障(如断网)会触发
catch。 -
HTTP 状态码非 2xx 时,
response.ok为false,需手动抛出错误。
3.5 表格总结:Fetch API 要点
| 要点 | 说明 | 示例 |
|---|---|---|
| 返回值 | fetch() 返回一个 Promise,resolve 值为 Response 对象 |
const promise = fetch(url); |
| 请求选项 | 第二个参数可配置 method、headers、body 等 | fetch(url, { method: 'POST', body: data }) |
| 解析响应 | 需调用 response.json() 等方法才能获得实际数据 |
response.json() 返回 Promise |
| 超时控制 | Fetch 本身不支持超时,可用 AbortController 实现 |
const controller = new AbortController(); signal: controller.signal |
| 跨域 | 遵循同源策略,需服务器支持 CORS | - |
四、综合实例:动态渲染汽车列表
下面结合箭头函数、Promise 和 Fetch,实现一个从 JSON 文件获取数据并渲染到页面的完整示例(源自题干代码)。
<div id="list"></div>
<script>
// 使用 fetch 请求数据,返回 Promise
fetch('./carList.json')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json(); // 返回解析后的数据 Promise
})
.then(data => {
const list = document.querySelector('#list');
// 使用箭头函数遍历数据,动态创建 DOM 元素
data.forEach(rowData => {
const item = document.createElement('div');
item.className = 'item';
item.innerHTML = `
<img src="${rowData.img}" alt="" class="item-img">
<div class="item-info">
<div class="item-name">${rowData.name}</div>
<div class="item-price">${rowData.price}</div>
</div>
`;
list.appendChild(item);
});
})
.catch(error => {
console.error('请求失败:', error.message);
});
</script>
考点解析:
-
箭头函数简化回调(
then和forEach中)。 -
Promise 链式调用处理异步。
-
Fetch 获取远程数据,结合 DOM 操作动态更新页面。
-
错误处理增强健壮性。
五、蓝桥杯 Web 考点关联与备考建议
5.1 常考题型
-
异步数据获取:要求使用 Fetch 或 Axios 获取 API 数据,并渲染到表格或列表中。
-
事件处理与 this 指向 :考察箭头函数在事件监听中保持外层
this的场景。 -
Promise 链式调用:给定多个异步任务,要求按顺序执行并处理结果。
-
错误捕获:要求对网络请求进行错误处理并显示友好提示。
5.2 备考要点
| 考点 | 掌握程度 | 练习建议 |
|---|---|---|
| 箭头函数的简写与 this | 熟练 | 对比普通函数与箭头函数在事件、定时器中的表现 |
| Promise 的三种状态与 API | 理解并能手写 | 实现简单的 Promise 封装,练习 Promise.all |
| Fetch 的基本用法 | 熟练 | 使用在线 API(如 jsonplaceholder)练习 GET/POST 请求 |
| 异步与 DOM 结合 | 综合应用 | 完成一个完整的"请求数据→渲染页面"小项目 |
六、总结
箭头函数、Promise 和 Fetch API 是现代 Web 开发的三把利剑。它们让异步代码更加优雅、可读、易于维护。在蓝桥杯 Web 赛项中,这些知识点几乎贯穿所有考题。通过本文的梳理,希望你能建立起清晰的知识框架,并结合表格与代码实例加深理解,在比赛中从容应对异步编程相关题目。