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 异步编程 | 菜鸟教程
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 异步编程在传统的同步(Synchronous)编程中,代码是按顺序执行的,每一行代码必须等待前一行代码执行完成后才能运行。而异步编程(Asynchronous)则允许代码在等待某些操作(如 I/O 操作)完成的同时继续执行其他任务,不会阻塞程序的运行。
Node.js 采用异步 I/O 模型,这使得它特别适合处理高并发的网络应用。理解异步编程是掌握 Node.js 的关键。 为什么 Node.js 需要异步编程Node.js 是单线程的,这意味着它一次只能执行一个任务。如果使用同步编程方式,当一个耗时操作(如读取大文件或网络请求)执行时,整个程序会被阻塞,无法处理其他请求。 异步编程解决了这个问题:
Node.js 异步编程的三种主要方式1、回调函数 (Callbacks)回调函数是 Node.js 中最基础的异步处理方式。它通过将一个函数作为参数传递给另一个函数,在操作完成后调用这个函数。 实例
const fs = require('fs');
// 异步读取文件 fs.readFile('example.txt', 'utf8', (err, data) => { if (err) { console.error('读取文件出错:', err); return; } console.log('文件内容:', data); }); console.log('读取文件请求已发送,继续执行其他代码...'); 特点:
2、PromisePromise 是 ES6 引入的异步编程解决方案,它表示一个异步操作的最终完成或失败及其结果值。 实例
const fs = require('fs').promises;
// 使用 Promise 读取文件 fs.readFile('example.txt', 'utf8') .then(data => { console.log('文件内容:', data); }) .catch(err => { console.error('读取文件出错:', err); }); console.log('读取文件请求已发送,继续执行其他代码...'); 特点:
3、async/awaitasync/await 是 ES8 引入的语法糖,基于 Promise,使异步代码看起来像同步代码。 实例
const fs = require('fs').promises;
async function readFile() { try { const data = await fs.readFile('example.txt', 'utf8'); console.log('文件内容:', data); } catch (err) { console.error('读取文件出错:', err); } } readFile(); console.log('读取文件请求已发送,继续执行其他代码...'); 特点:
错误处理最佳实践回调函数中的错误处理实例
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) { console.error('读取文件出错:', err); return; // 重要:处理错误后返回,避免执行后续代码 } console.log('文件内容:', data); }); Promise 的错误处理实例
fs.readFile('example.txt', 'utf8')
.then(data => { console.log('文件内容:', data); return someOtherAsyncOperation(data); }) .then(result => { console.log('第二步结果:', result); }) .catch(err => { console.error('处理过程中出错:', err); }); async/await 的错误处理实例
async function processData() {
try { const data = await fs.readFile('example.txt', 'utf8'); const result = await someOtherAsyncOperation(data); console.log('最终结果:', result); } catch (err) { console.error('处理过程中出错:', err); } } processData(); 性能考虑
AI 思考中...
点我分享笔记取消
分类导航
Advertisement
|
| You are visitor 01402775 — 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. |