GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing www.runoob.com — Node.js async/await | 菜鸟教程
Node.js 教程
Node.js 教程
Node.js 概念
Node.js 安装配置
Node.js VS Code
Node.js NVM
Node.js 创建第一个应用
Node.js 工作机制
NPM 使用介绍
PNPM 使用介绍
Node.js REPL
Node.js 异步编程
Node.js 回调函数
Node.js Promise
Node.js async/await
Node.js 事件循环
Node.js EventEmitter
Node.js Buffer
Node.js Stream
Node.js 模块系统
Node.js 模块导入
Node.js 函数
Node.js 路由
Node.js 全局对象
Node.js 常用工具
Node.js 文件系统
Node.js 内置模块
Node.js 测验
Node.js 应用Node.js 构建简单应用 Node.js GET/POST请求 Node.js util 模块 Node.js Web 模块 Node.js Express 框架 Node.js RESTful API Node.js 多进程 Node.js JXcore 打包 Node.js MySQL Node.js MongoDB npx 入门教程Node.js async/await在 Node.js 中,
使用
JavaScript 是单线程的,遇到异步任务(如 setTimeout 或网络请求)时,会交给 浏览器 API 处理,完成后将回调放入消息队列。 事件循环不断检查调用栈是否为空,如果是,就从队列中取出回调推入调用栈执行。这样既不会阻塞主线程,又能按顺序处理异步结果。 基本语法async 函数任何函数都可以通过添加
async function myFunction() {
return "Hello World"; }
await 表达式
async function fetchData() {
const response = await fetch('https://api.example.com/data'); const data = await response.json(); return data; } 错误处理try/catch 方式处理 实例
async function getUser() {
try { const response = await fetch('https://api.example.com/user'); const user = await response.json(); return user; } catch (error) { console.error('Error fetching user:', error); throw error; // 可以选择重新抛出错误 } } 直接处理 Promise你也可以直接处理返回的 Promise: 实例
getUser()
.then(user => console.log(user)) .catch(error => console.error(error)); 实际应用示例并行执行多个异步操作使用 实例
async function fetchMultipleUrls(urls) {
try { const requests = urls.map(url => fetch(url)); const responses = await Promise.all(requests); const data = await Promise.all(responses.map(r => r.json())); return data; } catch (error) { console.error('Error fetching data:', error); throw error; } } 数据库操作示例实例
async function getUserAndPosts(userId) {
try { const user = await User.findById(userId); const posts = await Post.find({ userId }); return { user, posts }; } catch (error) { console.error('Database error:', error); throw error; } } 最佳实践
常见问题async/await 与 Promise 的关系
为什么我的 async 函数返回 undefined?这可能是因为忘记在 可以在顶层使用 await 吗?在 ES 模块中(文件以 实例
// 在 ES 模块中
const data = await fetchData(); console.log(data);
AI 思考中...
点我分享笔记取消
分类导航
Advertisement
|
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |