全局值在函数内部不会改变

Global value doesn't change inside a function

我正在使用 formidable 来解析包含文本和上传图像的传入表单。但是,我无法使用 form.parse() 方法中的解析值更新那些全局变量(名称、描述等)。

如果我 console.log form.parse() 方法中的那个 newCampground 对象,每个字段值都会正确保存。但是,一旦我 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 }

form.parse 运行 异步 - 当你 console.log 在外面时,还没有 parsed。要么将处理新变量的所有功能放在回调中,要么将回调转换为 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();