await 实现 js
使用 async/await 实现异步操作
async/await 是 JavaScript 中处理异步操作的语法糖,基于 Promise 实现,使异步代码的书写更加简洁和直观。
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
处理多个异步操作
可以结合 Promise.all 来并行处理多个异步操作,提高效率。

async function fetchMultipleData() {
try {
const [userResponse, postsResponse] = await Promise.all([
fetch('https://api.example.com/users'),
fetch('https://api.example.com/posts')
]);
const user = await userResponse.json();
const posts = await postsResponse.json();
console.log(user, posts);
} catch (error) {
console.error('Error:', error);
}
}
在循环中使用 await
在循环中使用 await 需要谨慎,避免不必要的串行执行。

async function processItems(items) {
for (const item of items) {
const result = await processItem(item);
console.log(result);
}
}
错误处理的最佳实践
使用 try/catch 块来捕获和处理异步操作中的错误。
async function safeOperation() {
try {
const result = await potentiallyFailingOperation();
return result;
} catch (error) {
handleError(error);
throw error; // 可以选择重新抛出错误
}
}
在顶层使用 await
现代 JavaScript 环境支持在模块的顶层直接使用 await。
const data = await fetchData();
console.log(data);
注意:顶层 await 只能在 ES 模块中使用,不能在普通脚本中使用。






