1
votes

i have simple fs.readFile function to read json file data, get one of it's properties (array) and check if that array contains every single element of user generated array, and i use this code for this purpose

const contains = (arr1, arr2) =>
   arr2.every(v => arr1.indexOf(v) !== -1)

 fs.readFile('../tags.json', 'utf8', (err, data)=>{

    if(err) return res.status(500).send({message: err.message});

   var JsonData = JSON.parse(data);
   var tagsArray = JsonData.tags;
   console.log(tagsArray)
   console.log(tags)
   if(tagsArray instanceof Array){
     console.log('tagsArray is array')
   }
   var bool = contains(tagsArray, tags)
   if(!bool){
      return res.status(409).send({
        message: 'don't provide your own tags'
      })
   }

 })
  const user = await User.findById(req.userId, '-password').lean()

 const book = await Dish.create({
    //properties
 })

 return res.status(200).send({var: JSON.stringify(book)})

 } catch (error) {
     return res.status(500).send({
       message: error.message
     })
   }

i have try catch block inside the function (router.post) where fs.readFile is but it still gives me this message:

UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch().

and also this error:

UnhandledPromiseRejectionWarning: Error: Can't set headers after they are sent.

1
Well where is the promise rejection coming from? You dont show the code where the error is originating.GifCo
After calling this function do you call res.send?Ids van der Zee
yes but with 200 status code & in try catch block with 500 status codeiLiA
You can only call res.send once so your error is because you call res.send a second timeIds van der Zee
@GifCo console pointing me to a line where catch() is but i am sure problem is with this block because if i delete it code starts workingiLiA

1 Answers

1
votes
 const contains = (arr1, arr2) =>
   arr2.every(v => arr1.indexOf(v) !== -1)

 let match = false;
 fs.readFile('../tags.json', 'utf8', (err, data)=>{

   var JsonData = JSON.parse(data);
   var tagsArray = JsonData.tags;
   console.log(tagsArray)
   console.log(tags)
   if(tagsArray instanceof Array){
     console.log('tagsArray is array')
   }
   match = contains(tagsArray, tags)   

 });
 const user = await User.findById(req.userId, '-password').lean()

 const book = await Dish.create({
    //properties
 });

 if(!match){
    return res.status(409).send({
      message: 'don't provide your own tags'
    });
 }

 return res.status(200).send({var: JSON.stringify(book)})


 } 
 catch (error) {
     return res.status(500).send({
       message: error.message
     });
 }

You can try this, this should only call res.send once, either with 200, or 409, or 500 status codes.