Home > Enterprise >  Getting array empty [duplicate]
Getting array empty [duplicate]

Time:10-06

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.

CodePudding user response:

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([...]).

  • Related