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
重点!我是否可以异步执行此操作?