Node.js 有哪些异步写法?现在推荐哪种?

演进:回调 → Promise → async/await。

// 1) 回调(旧 API,易回调地狱)
fs.readFile('a.txt', 'utf8', (err, data) => { if (err) throw err })

// 2) Promise 版(推荐)
import { readFile } from 'fs/promises'
const data = await readFile('a.txt', 'utf8')

// 3) 事件回调(Stream / EventEmitter)
stream.on('data', chunk => {})

现在推荐 fs/promises + async/await,可读性好、便于 try/catch 统一错误处理。回调式 API(fs.readFile 无 promises 后缀)只在极低层或事件场景使用。

注意:await 必须在 async 函数里;顶层可用 top-level await(ESM + Node 14.8+)。

同分类其他题目