我是 Node/Express 新手。我有一系列长期运行的流程,例如:发布到 Express 端点 -> 保存数据(现在可以返回) -> 处理数据 -> 处理数据 -> 处理数据 -> 另一个进程 -> 等等
典型的帖子:
app.post("/foo", (req, res) => {
// save data and return
return res.send("200");
// but now I want to do a lot more stuff...
});
如果我省略return
,那么将会发生更多的处理,但即使我是这个堆栈的新手,我也知道这是一个坏主意。
我想要的只是接收一些数据,保存并返回。然后我想开始处理它,并调用其他进程,这些进程又调用其他进程,等等。我不希望原始 POST 等待这一切完成。
我需要在进程中执行此操作,因此我无法保存到队列并随后单独处理它。
基本上,我想在过程中将数据的接收和处理分解。
使用 Node/Express 可以使用哪些选项?
最佳答案
我会尝试这样的事情:
const express = require("express");
const port = 3000;
const app = express();
const uuid = require('uuid');
app.post("/foo", (req, res) => {
const requestId = uuid.v4();
// Send result. Set status to 202: The request has been accepted for processing, but the processing has not been completed. See https://tools.ietf.org/html/rfc7231#section-6.3.3.
res.status(202).json({ status: "Processing data..", requestId: requestId });
// Process request.
processRequest(requestId, request);
});
app.get("/fooStatus", (req, res) => {
// Check the status of the request.
let requestId = req.body.requestId;
});
function processRequest(requestId, request) {
/* Process request here, then perhaps save result to db. */
}
app.listen(port);
console.log(`Serving at http://localhost:${port}`);
用curl调用它(例如):
curl -v -X POST http://localhost:3000/foo
会给出如下响应:
{"status":"Processing data..","requestId":"abbf6a8e-675f-44c1-8cdd-82c500cbbb5e"}
关于node.js - 从 Node/Express 中长时间运行的 POST 中提前返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54088615/