我们如何在nodejs中使用async await ?
封面图
•
2026-01-08
•
nodejs
352
0
0
0
在 Node.js 中使用 `async/await` 是一种更简洁、更易读的方式来处理异步代码。它基于 **Promise**,可以让你以同步风格编写异步代码。 --- ## ✅ 一、基本用法 ### 1. 定义一个 `async` 函数 ```javascript async function myFunction() { // 异步操作 } ``` ### 2. 使用 `await` 等待 Promise 完成 ```javascript async function fetchData() { const response = await fetch('https://api.example.com/data'); const data = await response.json(); console.log(data); } ``` --- ## ✅ 二、完整示例(使用 `fs.promises`) Node.js 的一些模块(如 `fs`)也提供了 Promise 版本,你可以这样使用: ```javascript const fs = require('fs').promises; async function readFiles() { try { const data1 = await fs.readFile('file1.txt', 'utf8'); const data2 = await fs.readFile('file2.txt', 'utf8'); console.log('File 1:', data1); console.log('File 2:', data2); } catch (err) { console.error('Error reading files:', err); } } readFiles(); ``` --- ## ✅ 三、使用 `async/await` 和 `try/catch` 由于 `await` 会阻塞代码执行,所以建议将异步操作放在 `try/catch` 块中捕获错误: ```javascript async function main() { try { const result = await someAsyncFunction(); console.log('Result:', result); } catch (error) { console.error('Error:', error); } } main(); ``` --- ## ✅ 四、在 Express 中使用 `async/await` 你可以在 Express 路由中使用 `async/await`: ```javascript const express = require('express'); const app = express(); app.get('/data', async (req, res) => { try { const data = await fetchDataFromDatabase(); res.json(data); } catch (err) { res.status(500).send('Server error'); } }); app.listen(3000, () => { console.log('Server running on port 3000'); }); ``` --- ## ✅ 五、注意事项 - `async/await` 只能用于 **Promise** 对象。 - `await` 必须写在 `async` 函数内部。 - 不要滥用 `await`,否则会失去异步的优势(比如串行执行多个异步任务)。 --- ## ✅ 六、对比传统 Promise 写法 ### 传统写法(Promise): ```javascript fetch('https://api.example.com/data') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error)); ``` ### 使用 `async/await`: ```javascript 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); } } ``` --- 如果你有具体的场景或代码片段,我可以帮你进一步优化和解释!
上一篇:
什么是JavaScript中的一等函数 ?
下一篇:
如何在 nodejs 中创建一个返回 Hello World 的简单服务器
标题录入,一次不能超过6条
留言
评论