我正在使用强大的方法来解析包含文本和上传图像的传入表单。但是,我无法更新这些全局变量(名称,描述..等),以及 form.parse() 方法中的那些解析值。
如果我在form.parse()方法中控制台.log那个newCampground对象,则每个字段值都会正确保存。但是一旦我控制台.log解析方法之外的同一个新露营地对象,它就是空的。我花了 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);
上可能是无意的语法错误。
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();