【问题标题】:sending 'Response' when an operation is finished操作完成时发送“响应”
【发布时间】:2015-12-22 10:48:30
【问题描述】:

我正在使用Express 根据POST 请求的主体构建一堆文件。每当应用收到POST Request 时,它会调用一些长时间运行的函数来生成文件:

app.post('/test', function(req, res) {
    buildMyFiles(req.body);    // making files 
    res.send('got the post');
});

在创建所有文件之前,我不想发回任何响应。我该怎么做?

【问题讨论】:

  • 取决于buildMyFiles 的作用,但使用一些同步模式

标签: node.js asynchronous express


【解决方案1】:

你需要写buildMyFiles来支持异步回调事件:

app.post('/test', function(req, res) {
    buildMyFiles(req.body, function(err) {
        res.send('got the post');
    });
});

function buildMyFiles(body, callback) {
    /* 
    do lots of synchronous, long-running operations here
                    ^ emphasis

    if the build fails, define err (if the build succeeded, it'll be undefined)
    then execute the callback function 
    */

    callback(err);
}

如果您希望您的构建器是异步的,您可以考虑使用类似async 的东西来串行处理它们。由于我不知道您的 POST 请求是什么样的,因此我假设 body.files 是一个数组,而 buildFile 是您可能编写的另一个异步函数:

function buildMyFiles(body, callback) {
    async.each(body.files, function(file, callback) {
        buildFile(file, function(done) {
            callback()
        });
    }, function(err, results) {
       // async building is complete
       callback(err);
    });
}

【讨论】:

  • 呵呵,刚刚看到你的synchronous强调!无论如何我可以做到这一点asynchronously
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-16
  • 1970-01-01
  • 1970-01-01
  • 2015-01-07
  • 2015-12-06
  • 1970-01-01
相关资源
最近更新 更多