全局值不会在函数内部发生变化

时间:2018-04-04 00:11:19

标签: javascript node.js express global-variables formidable

我使用强大的方法来解析包含文本和上传图像的传入表单。但是,我无法使用form.parse()方法中的那些已解析值更新这些全局变量(name,dexcription..etc)。

如果我在form.log()方法中调用new.Campground对象,那么每个字段值都会正确保存。但是一旦我在parse方法之外的console.log同一个新的Campground对象,它就是空的。我花了2个小时试图解决这个问题,但我无法让它工作。任何帮助将不胜感激!

  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 }

1 个答案:

答案 0 :(得分:0)

form.parse异步运行 - 在您console.log之外的时候,它还没有parse。将所有功能都放在回调中处理新变量,或者将回调转换为Promise并对promise做.then,或者将回调转换为Promise并await承诺'决议。

我冒昧地修复console.log("Inside of parsed method);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();