我将
Multer
与自定义存储引擎一起使用,最终将文件上传到 Amazon S3。由于文件将发送到 Amazon S3,然后发回有关该文件的一些信息,因此我必须等待整个 Multer
中间件完成才能执行其他操作。
这是我的 Express 路线的示例:
const multer = require('multer')
const upload = multer({
storage: MulterS3Storage, // This is a custom storage engine which works
});
app.post('/form', upload.single('uploaded_file'), function (req, res) {
console.log('I MUST wait for upload.single to finish');
Result = {
code: 200,
files: req.file, // from Multer with metadata in it about the file e.g. file.location
}
return res.status(Result.code).json(Result); // this runs before Multer has returned the callback
});
不幸的是,它没有等待
upload.single
完成。也就是说,在 console.log
使用 res.status
中的正确信息运行回调之前,路由会执行 MulterS3Upload
并返回 req.file
。
在我看来,我似乎需要
await
upload.single(uploaded_file)
部分,但不知道该怎么做?
您的代码正在使用带有
async
的 callback
调用..,这与可以正确执行某些操作的 Promise
不同。所以,而不是:await
您可能想使用包装器:
app.post('/form', upload.single('uploaded_file'), function (req, res) {
console.log('I MUST wait for upload.single to finish');
Result = {
code: 200,
files: req.file, // from Multer with metadata in it about the file e.g. file.location
}
return res.status(Result.code).json(Result); // this runs before Multer has returned the callback
});
然后您可以使用以下命令等待它:
function MyAsyncApiCall() {
return new Promise((resolve, reject) => {
app.post('/form', upload.single('uploaded_file'), function (req, res) {
console.log('I MUST wait for upload.single to finish');
Result = {
code: 200,
files: req.file, // from Multer with metadata in it about the file e.g. file.location
}
resolve(Result);
});
});
}
此代码应该改进(例如功能参数),并且可能无法按您的预期工作..但是..添加一些调整 - 这就是您的了!