1

I am using formidable to parse an incoming form which contains both text and an uploaded image. However, I am not able update those global variables(name, dexcription..etc) with those parsed values inside the form.parse() method.

If I console.log that newCampground object inside the form.parse() method, every field value is saved properly. But as soon as I console.log the same new Campground object outside of the parse method, it is empty. I have spent 2 hrs trying to fix this but I can't get it to work. Any help will be appreciated!

  var name;
  var description;
  var price;
  var image;
  var author = {
          id: req.user._id,
          username: req.user.username
  };
  var newCampground = {name: name,
                     image: image,
                     description: description,
                     author: author,
                     price: price,
                     uploadImage: uploadImage
                     } ;

var form = formidable.IncomingForm();
form.parse(req, function(err, fields, files){

   newCampground["name"] = fields.name;
   newCampground.description = fields.description;
   newCampground.price = fields.price;
   newCampground.image = fields.image;
   console.log("Inside of parsed method);
   console.log(JSON.stringify({newCampground}));//this one has everything
});
console.log("Outside of parsed method);
console.log(JSON.stringify({newCampground}));//nothing inside

// ===============console output==================//
Outside of parsed method
{"newCampground":{"author":{"id":"5ab8893a4dd21b478f8d4c40","username":"jun"}}}
Inside of parsed method
{"newCampground":{"name":"aaaaa","image":"","description":"ddddd","author":{"id":"5ab8893a4dd21b478f8d4c40","username":"jun"},"price":"vvvvv","uploadImage":"/uploads/i.jpg"}}
{ author: { id: 5ab8893a4dd21b478f8d4c40, username: 'jun' },
  comments: [],
  _id: 5ac4164432f6902a2178e877,
  __v: 0 }
kjunz
  • 111
  • 1
  • 7
  • 1
    `form.parse()` appears to operate asynchronously… [Why is my variable unaltered after I modify it inside of a function?](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Jonathan Lonowski Apr 04 '18 at 00:16
  • @JonathanLonowski thanks for your help! that question helped me to understand how asynchronicity works!! – kjunz Apr 04 '18 at 08:29

1 Answers1

0

form.parse runs asynchronously - at the time you console.log outside, it hasn't been parsed yet. Either put all your functionality dealing with the new variables inside the callback, or turn the callback into a Promise and do .then on the promise, or turn the callback into a Promise and await the promise's resolution.

I took the liberty of fixing what were probably unintentional syntax errors on console.log("Inside of parsed method); and console.log("Outside of parsed method);.

async function myFunc() {
  var name;
  var description;
  var price;
  var image;
  var author = {
    id: req.user._id,
    username: req.user.username
  };
  var newCampground = {
    name: name,
    image: image,
    description: description,
    author: author,
    price: price,
    uploadImage: uploadImage
  };

  var form = formidable.IncomingForm();
  await new Promise(resolve => {
    form.parse(req, function(err, fields, files) {
      newCampground["name"] = fields.name;
      newCampground.description = fields.description;
      newCampground.price = fields.price;
      newCampground.image = fields.image;
      console.log("Inside of parsed method");
      console.log(JSON.stringify({
        newCampground
      }));
      resolve();
    });
  });
  console.log("Outside of parsed method");
  console.log(JSON.stringify({
    newCampground
  }));
}
myFunc();
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320