js实现async
async/await 基本用法
在 JavaScript 中,async/await 是基于 Promise 的语法糖,用于简化异步操作。async 函数会返回一个 Promise 对象,而 await 只能在 async 函数内部使用。
async function fetchData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
}
错误处理
使用 try/catch 结构来处理 async/await 中的错误:
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
} catch (error) {
console.error('Error:', error);
}
}
并行执行多个异步操作
使用 Promise.all 来并行执行多个异步操作:
async function fetchMultipleData() {
const [data1, data2] = await Promise.all([
fetch('https://api.example.com/data1').then(res => res.json()),
fetch('https://api.example.com/data2').then(res => res.json())
]);
return { data1, data2 };
}
async 函数的返回值
async 函数总是返回一个 Promise。如果函数返回一个非 Promise 值,它会被自动包装成一个 resolved Promise:
async function getValue() {
return 42;
}
getValue().then(value => console.log(value)); // 42
在循环中使用 await
在循环中使用 await 时需要注意顺序执行和并行执行的区别:
// 顺序执行
async function processArray(array) {
for (const item of array) {
await processItem(item);
}
}
// 并行执行
async function processArrayParallel(array) {
await Promise.all(array.map(item => processItem(item)));
}
立即执行 async 函数
使用 IIFE (立即调用函数表达式) 模式来立即执行 async 函数:
(async () => {
const result = await fetchData();
console.log(result);
})();
在类方法中使用 async
可以在类方法中使用 async:
class ApiClient {
async getData() {
const response = await fetch('https://api.example.com/data');
return response.json();
}
}
顶层 await
在现代 JavaScript 中,可以在模块的顶层使用 await:

const data = await fetchData();
console.log(data);
注意:顶层 await 只能在 ES 模块中使用,不能在普通脚本中使用。






