Answer the question
In order to leave comments, you need to log in
How to return data received from a callback function?
There is a service that works with the database and returns the result of its work to the controller ... inside the ODM mongoose it has an asynchronous save method that takes as arguments, among other things, a callback function in which I process the save result and generate the answer I need !!! and at this moment the question arises HOW do I get the result of this work of the callback function ????
async createService(createService: ServicesDto): Promise<ServicesOutsideDto> {
try {
const createdService = new this.servicesModel(createService);
let res: IServices;
createdService.save(async(err) => {
try {
if(!err) {
return await this.servicesModel.findOne({'_id': createdService._id}).populate('banner').exec();
}else throw err;
}catch (error) {
throw error;
}
}).then((data) => {
res = data;
});
return plainToClass<ServicesOutsideDto, object>(
ServicesOutsideDto,
res.toObject(),
{excludePrefixes: ["_"]}
);
}catch (error) {
if(error && error.name === 'ValidationError'){
throw new BadRequestException(error);
} else throw error;
}
}
Answer the question
In order to leave comments, you need to log in
Something like this:
async createService(createService: ServicesDto): Promise<ServicesOutsideDto> {
try {
const createdService = new this.servicesModel(createService);
let res: IServices = await new Promise((resolve, reject)=>{
createdService.save(async(err) => {
try {
if(!err) {
resolve(this.servicesModel.findOne({'_id': createdService._id}).populate('banner').exec());
}else throw err;
}catch (error) {
reject(error)
}
})
})
return plainToClass<ServicesOutsideDto, object>(
ServicesOutsideDto,
res.toObject(),
{excludePrefixes: ["_"]}
);
}catch (error) {
if(error && error.name === 'ValidationError'){
throw new BadRequestException(error);
} else throw error;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question