如何让Node.js代码等待Cloudinary上传完成后再返回前端响应?
问题解决方案
核心问题在于你使用的cloudinary.uploader.upload_large是回调式API,而你的largeFileUploader函数虽然标记了async,但并未正确包裹Promise来等待回调完成,导致await无法生效,代码直接跳过上传流程提前返回。以下是具体修复步骤:
1. 将Cloudinary上传函数转为Promise风格
修改largeFileUploader,用Promise包裹回调逻辑,让await能正确等待上传结果:
export const largeFileUploader = async(props: {targetedFile: string})=>{ const {targetedFile} = props; return new Promise((resolve, reject) => { cloudinary.uploader.upload_large( targetedFile, { resource_type: "video", chunk_size: 6000000, folder: 'folderName', upload_preset: 'presetName' }, function(error, result) { if(error) { console.log(error, 'error'); reject('Error encountered'); return; } resolve(result); } ); }); };
2. 修正路由调用函数的变量问题并添加MongoDB存储逻辑
你的imageUploadFunct中file变量未定义,需要从files数组中获取文件,同时在拿到Cloudinary的上传结果后,添加MongoDB存储操作:
// 假设你已导入MongoDB对应的模型,比如: // import VideoRecord from '../models/VideoRecord'; const imageUploadFunct = async(req: Request, res: Response, eventType: events)=>{ const files = req?.files as Express.Multer.File[]; const imageUrl: string[] = []; const publicId: string[] = []; if(eventType === 'video_upload_event'){ if(!files?.length) throw 'No video file uploaded'; const file = files[0]; // 获取上传的第一个视频文件 const uploadResponse = await largeFileUploader({targetedFile: file.path}) as any; // 存储到MongoDB await VideoRecord.create({ videoUrl: uploadResponse.secure_url, publicId: uploadResponse.public_id // 可添加其他业务字段,比如上传时间、关联用户ID等 }); imageUrl.push(uploadResponse.secure_url); publicId.push(uploadResponse.public_id); if(file.path){ removeFile({filePath: file.path}); }; return { imageUrl, publicId }; } };
3. 保持控制器逻辑不变
你的httpUploadVideo控制器已经正确使用await等待imageUploadFunct完成,无需修改,现在整个流程会按顺序执行:
- 等待Cloudinary上传完成
- 将结果存储到MongoDB
- 删除本地临时文件
- 向前端返回最终结果
内容的提问来源于stack exchange,提问作者valve
相关产品推荐
相关产品推荐

