Return 早于 long-运行 POST 在 Node/Express

Return early from long-running POST in Node/Express

我是 Node/Express 的新手。我有一个很长的-运行系列过程,例如:post to Express endpoint -> save data (can return now) -> handle data -> handle data -> handle data -> another process -> etc.

一个典型的POST:

app.post("/foo", (req, res) => {
  // save data and return
  return res.send("200");
  // but now I want to do a lot more stuff...
});

如果我省略 return 则会进行更多处理,但即使我是这个堆栈的新手,我也可以说这是个坏主意。

我只想接收一些数据,保存并 return。然后我想开始处理它,并调用其他进程,调用其他进程等。我不想原来POST等待所有这些完成。

我需要在进程中执行此操作,因此我无法保存到队列并在之后单独处理它。

基本上我想在处理过程中分离数据的接收和处理。

使用 Node/Express 可以使用哪些选项?

您在此处删除 return 并结束请求的方法绝对没有错......只要您没有任何其他代码稍后会尝试发回任何数据.

不过,我建议为这些较长的 运行 场景返回状态代码 202 Accepted,这向消费者表明服务器已接受请求但尚未完成。

我会尝试这样的事情:

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"}