繁体   English   中英

全局值在函数内部不变

[英]Global value doesn't change inside a function

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

如果我在form.parse()方法内console.log该newCampground对象,则每个字段值都将正确保存。 但是,只要我在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 }

form.parse 异步运行-在您外部进行console.log ,尚未对其进行parse 要么把所有的功能处理回调里面的新的变量,或将回调到一个承诺,做.then广阔的前景,或将回调到一个承诺, await承诺的分辨率。

我自由地修复了console.log("Inside of parsed method);console.log("Outside of parsed method); 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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM