0

I'm working with this code to delete some images using an array with the URL. It works fine, however when I want to return another array with the deleting status of each one, I get an empty array.

import fs from 'fs';
import path from 'path';
const pathStatic = path.join(__dirname, "../..", "public");

export const deleteImages = (images) => {
       return images.map ((image) => {

        fs.unlink(path.join(pathStatic, image), (err) => {

        if (err) {
            return {
              status: 'error',
              msg: 'The image could not be deleted.',
              url: image
              };
            }
            else{
                return {
                status: 'success',
                msg: 'The image was deleted successfully.',
                url: image
             };
           }
         });
      });
}

Not so sure what could be the issue.

  • 4
    `unlink` is async. The values you return from its callback won't be returned in the `map` callback – Phil Oct 06 '21 at 01:09
  • 5
    Asynchronicity. Any return from a callback to an asynchronous function like `fs.unlink` is ignored in the present because it will resolve in the future. The easiest way to do this is to use the promisified functions (`fs.promises.unlink`), and `Promise.all` to collect the results into a single promise that will produce the results. – Amadan Oct 06 '21 at 01:11
  • 2
    This is relevant: [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Amadan Oct 06 '21 at 01:13

1 Answers1

3

As the commenters have said, you are mixing sync and async code, callbacks and maps. The best way to do this today in 2021 is to go full-async and write the code like this:

import fs from "fs/promises";
import path from "path";
const pathStatic = path.join(__dirname, "../..", "public");

export const deleteImages = images => {
  return Promise.all(images.map(async image => {
    try {
      await fs.unlink(path.join(pathStatic, image));
      return {
        status: "success",
        msg: "The image was deleted successfully.",
        url: image
      };
    } catch (error) {
      return {
        status: "error",
        msg: "The image could not be deleted.",
        url: image
      };  
    }
  }));
};

You'd then call it with await deleteImages([...]).

Francisco Presencia
  • 8,732
  • 6
  • 46
  • 90