簡體   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