
在 node.js 和 express.js 开发中,处理异步操作是核心技能。当一个 api 请求需要执行多个独立的、耗时的任务(例如,并发请求外部服务、读写文件等)时,我们通常会使用 promise 来管理这些操作。promise.all 是一个非常有用的工具,它允许我们并行地执行一组 promise,并等待它们全部成功完成。如果所有 promise 都成功,promise.all 返回一个包含所有 promise 结果的数组;如果其中任何一个 promise 失败,promise.all 会立即拒绝,并返回第一个拒绝的 promise 的错误。
结合 ES2017 引入的 async/await 语法,我们可以用同步代码的风格来编写异步逻辑,使得代码更易读、更易维护。一个 async 函数总是返回一个 Promise,而 await 关键字只能在 async 函数内部使用,它会暂停 async 函数的执行,直到其后的 Promise 解决(resolved)或拒绝(rejected)。
在处理多个并发异步任务时,开发者常遇到的一个问题是,尽管使用了 Promise.all,API 却似乎没有等待所有任务完成就发送了响应。这通常是由于以下一个或多个原因造成的:
让我们看一个初始的错误示例:
// app.post 路由处理器 (可能存在问题)
app.post('/', async (req: Request, res: Response) => {
const tasksRequest = req.body as TasksRequest;
let tasks: Promise<any>[] = [];
// 这里的 await Promise.all(tasks) 看起来正确,但如果 processTask 有问题,可能仍无法等待
tasks = tasksRequest.tasks.map((t) => processTask(t, tasksRequest.configs));
await Promise.all(tasks); // 问题可能出在 processTask 的实现或后续没有发送响应
// ... 缺少 res.send() 或 res.json()
});
// processTask 函数 (使用回调风格的 fs.writeFile,且错误处理不完善)
function processTask(task: Task, configs: Configs) {
return new Promise<void>((resolve, reject) => {
try {
const fileName = './output/' + task.tag + 's.json';
fetch(configs.Host + configs.APIsBasePrefix + task.parentResource + task.mostRelatedPath, {
method: 'GET'
}).then(result => {
result.json().then(jsonResult => {
// fs.writeFile 是回调风格,需要检查 err 并 reject
fs.writeFile(fileName, JSON.stringify(jsonResult), function () {
console.log('finished writing :' + fileName);
resolve();
});
}).catch(err => reject(err));
}).catch(err => reject(err));
} catch (err) {
console.log(err); // 这里的 catch 只能捕获同步错误
}
});
}在这个 processTask 的初始版本中,fs.writeFile 是一个回调函数,其回调中并没有检查 err 参数并调用 reject(err)。这意味着即使文件写入失败,外部的 Promise 也可能被 resolve(),导致 Promise.all 无法感知到这个内部的失败。
另一个常见的错误是在 async 函数中,虽然使用了 Promise.all,但却没有 await 它,或者在 await 之后又错误地使用了 .then():
// app.post 路由处理器 (缺少 await Promise.all)
app.post('/', async (req: Request, res: Response) => { // 声明为 async 是正确的
const tasksRequest = req.body as TasksRequest;
let tasks = [];
tasks = tasksRequest.tasks.map( (t) => processTask(t, tasksRequest.configs));
// 这里的 Promise.all(tasks).then(...) 没有被 await
// 导致路由处理器会立即继续执行,可能在任务完成前就结束
Promise.all(tasks).then(results => {
console.log('After awaiting');
// ... 应该在这里发送响应,但如果这里没有 res.send(),外部也无法收到响应
});
// 如果这里没有 res.send(),且上面的 Promise 没被 await,API 将挂起或超时
});为了解决上述问题,我们应该采用现代 JavaScript 的 async/await 语法,并利用 Node.js fs 模块的 Promise 版本 (fs.promises),这能大大提高代码的可读性和健壮性。
将 processTask 函数转换为 async 函数,并使用 await 来处理异步操作,包括 fetch 请求和文件写入。
import * as fs from 'fs/promises'; // 导入 fs.promises
import fetch from 'node-fetch'; // 如果在 Node.js 环境,可能需要安装 node-fetch
// 定义类型 (假设已定义)
interface Task {
tag: string;
parentResource: string;
mostRelatedPath: string;
}
interface Configs {
Host: string;
APIsBasePrefix: string;
}
async function processTask(task: Task, configs: Configs): Promise<void> {
try {
const fileName = `./output/${task.tag}s.json`;
// 使用 await 等待 fetch 请求完成
const result = await fetch(configs.Host + configs.APIsBasePrefix + task.parentResource + task.mostRelatedPath, {
method: 'GET'
});
// 使用 await 等待 JSON 解析完成
const jsonResult = await result.json();
// 使用 fs.promises.writeFile,它返回一个 Promise,可以直接 await
await fs.writeFile(fileName, JSON.stringify(jsonResult));
console.log(`finished writing: ${fileName}`);
} catch (err) {
console.error(`Error processing task ${task.tag}:`, err);
// 捕获并重新抛出错误,以便 Promise.all 能够感知到
throw err;
}
}说明:
确保 Express.js 路由处理函数被声明为 async,并且在调用 Promise.all 时使用 await 关键字。
import express, { Request, Response } from 'express';
// ... 其他导入,如 processTask 函数
const app = express();
app.use(express.json()); // 用于解析请求体
// 定义类型 (假设已定义)
interface TasksRequest {
tasks: Task[];
configs: Configs;
}
app.post('/', async (req: Request, res: Response) => {
try {
const tasksRequest = req.body as TasksRequest;
// 映射任务为 Promise 数组
const tasks: Promise<void>[] = tasksRequest.tasks.map((t) =>
processTask(t, tasksRequest.configs)
);
console.log('Starting to process tasks...');
// 使用 await 等待所有 Promise 完成
// Promise.all 会等待所有任务成功,如果任何一个失败,它会立即拒绝
await Promise.all(tasks);
console.log('All tasks finished successfully.');
// 所有任务完成后,发送成功响应
res.status(200).json({ message: 'All tasks processed successfully.' });
} catch (error) {
console.error('An error occurred during task processing:', error);
// 捕获任何一个任务失败的错误,并发送错误响应
res.status(500).json({ message: 'Failed to process some tasks.', error: (error as Error).message });
}
});
// 启动服务器 (示例)
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});说明:
通过以上重构,我们实现了在 Express.js API 中等待多个 Promise 完成再发送响应的健壮机制。
关键点总结:
遵循这些最佳实践,可以构建出高效、稳定且易于维护的 Express.js 异步 API。
以上就是Express.js 中等待多个 Promise 完成再响应的策略的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号