当操作完成时发送“响应”
我正在使用Express
来build立一堆基于POST
请求正文的文件。 每当应用程序收到一个POST Request
,它将调用一些长时间运行的函数来生成这些文件:
app.post('/test', function(req, res) { buildMyFiles(req.body); // making files res.send('got the post'); });
我不想发送任何回应,直到所有的文件被创build。 我怎么能做到这一点?
您需要编写buildMyFiles
来支持asynchronouscallback事件:
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); }
如果你想让你的构build器是asynchronous的,你可以考虑使用类似async
来处理它们。 由于我不知道你的POST请求是什么样的,我假设body.files
是一个数组,而buildFile
是另一个asynchronous函数,你可能会这样写:
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); }); }