0

i tried 3 days ago for read image from backend and this best solution i'm tried but i got error and don't understand the error

please help

  get_image:(req,res)=>{
const directoryPath = __basedir + "/uploads/";
const baseUrl = "http://localhost:8080/test/get_image/";
fs.readdir(directoryPath,  function (err, files) {
  if (err) {
    res.status(500).send({
      message: "Unable to scan files!",
    });
  }
  let fileInfos = [];
  files.forEach(Image.findAll().then(data=>{   <<=== error here 
    fileInfos.push({
      name: data.name,
      url:  baseUrl+data.name,
    });
  }))
})
   }

Error :

 files.forEach(Image.findAll().then(data=>{
        ^
TypeError: #<Promise> is not a function
yaser OtakU
  • 35
  • 1
  • 9
  • 1
    `.forEach( foo )` expects `foo` to be a function that will be executed for each element. However in your case `foo = Image.findAll().then( /* ... */ )` which is a promise, not a function. – VLAZ Dec 04 '20 at 12:07
  • You have passed a `Promise` to `files.forEach(...)` instead of a callback function. – Yousaf Dec 04 '20 at 12:09
  • same problem : files.forEach(foo) =>TypeError: # is not a function – yaser OtakU Dec 04 '20 at 12:15
  • That's exactly what I tried to explain... you cannot pass a promise to `forEach`. And I don't know what you're attempting to do, so I can't tell you what the correct code is. – VLAZ Dec 04 '20 at 12:25

2 Answers2

0

Try this out:

  get_image: (req, res) => {
    const directoryPath = __basedir + "/uploads/";
    const baseUrl = "http://localhost:8080/test/get_image/";
    fs.readdir(directoryPath, async function(err, files) {
      if (err) {
        res.status(500).send({
          message: "Unable to scan files!"
        });
      }
      let data = await Image.findAll();
      let fileInfos = files.map(file => ({
        name: data.name,
        url: baseUrl + data.name
      }));
    });
  }

Instead of iteration over and over again you could fetch data once and then map it

bill.gates
  • 14,145
  • 3
  • 19
  • 47
0

Replace your code block

files.forEach(Image.findAll().then(data=>{   <<=== error here 
    fileInfos.push({
      name: data.name,
      url:  baseUrl+data.name,
    });
  }))

to

const responseList = await Promise.all(
    files.map(() => {
        return Image.findAll().then(data => {
            return fileInfos.push({
                name: data.name,
                url: baseUrl + data.name,
            });
        })
    })
)

Then it will work. I have used Promise.all to run all the request in parallel

AndroidEngineX
  • 975
  • 1
  • 9
  • 22