Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

105
Views
Cómo devolver la promesa de fs.unlink

Quiero eliminar un archivo y esperar a que la eliminación se realice correctamente antes de continuar. He usado la función de desvinculación dentro de una promesa para obtener el resultado, pero cuando la desvinculación se realiza con éxito, obtengo el resultado de la promesa si hay algún error al eliminar el archivo, la promesa no devuelve ningún error.

Servicio:

 public removeUserImage( user: User, ): Promise<NodeJS.ErrnoException | boolean> { const pathToRemoveImage = 'src/public/uploads'+ '/' + user.image_url; return new Promise((resolve, reject) => { unlink(pathToRemoveImage, (error) => { if (error) reject(error); resolve(true); }); }); }

Controlador:

 const isFileRemoved = await this._userService.removeUserImage(user); //This block not excuting if (!isFileRemoved) { throw new InternalServerErrorException( 'Error occurred while trying to remove file.', ); }
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Su promesa se rechaza si hay un error. Al usar await , debe envolver el código en try..catch para manejar cualquier falla

 try { await this._userService.removeUserImage(user); } catch (err) { console.error(err); throw new InternalServerErrorException( 'Error occurred while trying to remove file.' ); }

FYI, puede (y debe) usar las versiones de API de Promises de las funciones fs

 import { unlink } from "node:fs/promises"; public removeUserImage({ image_url }: User): Promise<void> { const pathToRemoveImage = `src/public/uploads/${image_url}`; return unlink(pathToRemoveImage); }

Si quisiera que su método siempre se resolviera con un booleano, querría algo como

 return unlink(pathToRemoveImage) .then(() => true) // resolve with "true" for success .catch((err) => { console.error("removeUserImage", image_url, err); return false; // resolve with "false" for failure });
about 4 years ago · Juan Pablo Isaza Report

0

El error siempre irá al bloque catch,

 try { await this._userService.removeUserImage(user); } catch (err) { console.error(err); throw new InternalServerErrorException( 'Error occurred while trying to remove file.' ); }

Sugerencia: no necesita convertir unlink (devolución de llamada) para prometer que fs también tiene una función de promesa, verifique esto

 const fs = require('fs'); const fsPromises = fs.promises; public removeUserImage( user: User, ): Promise<void> { const pathToRemoveImage = 'src/public/uploads'+ '/' + user.image_url; return fsPromises.unlink(pathToRemoveImage); }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!