Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 发送';答复';当一个操作完成时_Node.js_Asynchronous_Express - Fatal编程技术网

Node.js 发送';答复';当一个操作完成时

Node.js 发送';答复';当一个操作完成时,node.js,asynchronous,express,Node.js,Asynchronous,Express,我正在使用Express根据POST请求的主体构建一组文件。每当应用程序收到POST请求时,它都会调用一些长时间运行的函数来生成文件: app.post('/test', function(req, res) { buildMyFiles(req.body); // making files res.send('got the post'); }); 在创建所有文件之前,我不想发送任何响应。我如何做到这一点?您需要编写buildMyFiles来支持异步回调事件: app

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

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

在创建所有文件之前,我不想发送任何响应。我如何做到这一点?

您需要编写
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);
}

如果你想让你的建造者是异步的,你可以考虑使用一些类似于<代码>异步的< /代码>来处理它们。因为我不知道您的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);
    });
}

取决于
buildMyFiles
做了什么,但是使用了一些同步模式哈,刚才看到了你的
synchronous
重点!我是否可以异步执行此操作?