[英]i want to return a response of an array of image links after uploading to cloudinary in nestjs
so i need a way to delay the return statement in the controller until the foreach loop is done.所以我需要一种方法来延迟 controller 中的 return 语句,直到 foreach 循环完成。 i just need to properly handle the asynchronous operation and i don't know how else
我只需要正确处理异步操作,我不知道怎么办
the response returns an empty array because the array is populated after the response is returned响应返回一个空数组,因为数组是在返回响应后填充的
uploads.controller.ts上传.controller.ts
import {
Controller,
Post,
UseInterceptors,
UploadedFiles,
} from '@nestjs/common';
import { FilesInterceptor } from '@nestjs/platform-express';
import { UploadsService } from './uploads.service';
import { v2 as cloudinary } from 'cloudinary';
@Controller('attachments')
export class UploadsController {
constructor(private readonly uploadsService: UploadsService) {}
@Post('images')
@UseInterceptors(FilesInterceptor('attachment'))
async uploadFile(@UploadedFiles() attachment: Array<Express.Multer.File>) {
cloudinary.config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET,
secure: true,
});
const response = [];
await attachment.forEach(async (file) => {
const fileResponse = await this.uploadsService.uploadImage(file);
response.push(fileResponse.secure_url);
console.log('1', response);
});
console.log('2', response);
return await response;
}
}
uploads.service.ts上传.service.ts
import { UploadApiErrorResponse, UploadApiResponse, v2 } from 'cloudinary';
import toStream = require('buffer-to-stream');
@Injectable()
export class UploadsService {
async uploadImage(
file: Express.Multer.File,
): Promise<UploadApiResponse | UploadApiErrorResponse> {
return new Promise((resolve, reject) => {
const upload = v2.uploader.upload_stream((error, result) => {
if (error) return reject(error);
resolve(result);
});
toStream(file.buffer).pipe(upload);
});
}
}
The problem is here.问题就在这里。
await attachment.forEach(async (file) => {
const fileResponse = await this.uploadsService.uploadImage(file);
response.push(fileResponse.secure_url);
console.log('1', response);
});
Don't pass async function to Array.forEach
.不要将 async function 传递给
Array.forEach
。 Check out this question .看看这个问题。
This will work.这会起作用。
const response = await Promise.all(attachment.map(async (file) => {
const fileResponse = await this.uploadsService.uploadImage(file);
return fileResponse.secure_url;
}));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.