async 实现 js
async 实现 JavaScript 异步编程
在 JavaScript 中,async/await 是基于 Promise 的语法糖,用于简化异步代码的编写,使其更接近同步代码的风格。
基本语法
使用 async 关键字声明一个异步函数,该函数会返回一个 Promise 对象。在异步函数内部,可以使用 await 关键字等待 Promise 的解决。
async function fetchData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
}
错误处理
使用 try/catch 块捕获异步操作中的错误,确保代码的健壮性。
async function fetchDataWithHandling() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
} catch (error) {
console.error('Error fetching data:', error);
throw error;
}
}
并行执行多个异步操作
使用 Promise.all 并行执行多个异步操作,提高效率。
async function fetchMultipleData() {
const [userData, postData] = await Promise.all([
fetch('https://api.example.com/users').then(res => res.json()),
fetch('https://api.example.com/posts').then(res => res.json())
]);
return { userData, postData };
}
注意事项
await 只能在 async 函数中使用,否则会抛出语法错误。在全局作用域或非异步函数中直接使用 await 会导致错误。
// 错误示例
function nonAsyncFunction() {
const data = await fetchData(); // SyntaxError
}
实际应用示例
结合 async/await 处理 API 请求,简化回调地狱问题。

async function getUserPosts(userId) {
const user = await fetch(`https://api.example.com/users/${userId}`);
const posts = await fetch(`https://api.example.com/users/${userId}/posts`);
return { user, posts };
}
getUserPosts(1)
.then(data => console.log(data))
.catch(error => console.error(error));
通过 async/await,JavaScript 的异步代码变得更加清晰和易于维护。






