// 使用 async/await 的示例代码
// 定义一个异步函数,使用 async 关键字
async function fetchUserData(userId) {
try {
// 模拟网络请求,使用 await 等待 Promise 完成
const response = await fetch(`https://api.example.com/users/${userId}`);
// 检查响应是否成功
if (!response.ok) {
throw new Error('Network response was not ok');
}
// 解析 JSON 数据
const data = await response.json();
// 返回用户数据
return data;
} catch (error) {
// 捕获并处理错误
console.error('There was a problem with the fetch operation:', error);
return null;
}
}
// 调用异步函数并处理结果
async function main() {
const userId = 123;
const user = await fetchUserData(userId);
if (user) {
console.log('User data:', user);
} else {
console.log('Failed to fetch user data.');
}
}
// 执行主函数
main();
async
关键字用于定义一个异步函数,该函数会返回一个 Promise
。在函数内部,可以使用 await
来等待异步操作完成。await
关键字用于等待一个 Promise
完成,并获取其结果。它只能在 async
函数中使用。try...catch
块来捕获和处理可能的错误,确保程序不会因为未处理的异常而崩溃。fetch
是一个用于发起 HTTP 请求的内置 API,返回一个 Promise
,解析后可以获得响应数据。这个示例展示了如何使用 async
和 await
来简化异步代码的编写,使代码更易读且更易于维护。
下一篇:js 运算符
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站