我正在使用promise来从DB获取值,并且我想在db中搜索在表单提交(req.body.country)之后检索的值,获取其id并将其分配给声明的变量承诺,如何获得它? 这是代码:
var newAddress = new Address(); // Address is a mongoose model.
newAddress.city = req.body.city;
newAddress.state = req.body.state;
Country
.findOne({name: req.body.country})
.then(function (result) {
newAddress.country = result;
})
.catch(function(err) {
res.send(500, {message: 'Failed to search into DB'});
});
newAddress.save(function (err, result) {
if(err) {
res.status(500).send('Failed to save the newAddress to DB: ' + err);
}
});
这是猫鼬地址模型:
var addressSchema = new Schema({
street1: {type: String, required: true},
street2: String,
city: String,
state: String,
zip: String,
country: {type: Schema.Types.ObjectId, ref: 'Country'},
lat: String,
long: String
});
一切都在嵌套回调中,我正试图从回调转向Promise。 我没有错误,它只是没有将国家保存在地址中,因为promise中的newAddress与代码开头声明的newAddress不同
答案 0 :(得分:1)
将newAddress.save()
方法移至then
回调
var newAddress = new Address(); // Address is a mongoose model.
Country.findOne({name : req.body.country})
.then(function (result) {
newAddress.country = result;
newAddress.save(function (err, result) {
if (err) {
res.status(500).send('Failed to save the newAddress to DB: ' + err);
}
});
})
.catch(function (err) {
res.send(500, {message : 'Failed to search into DB'});
});
请详细了解Promise
以及如何从异步功能返回。
答案 1 :(得分:1)
newAddress.save()
返回承诺)。catch
处理程序处理所有可能的错误。代码:
Country
.findOne({ name : req.body.country })
.then(country => {
let address = new Address({
city: req.body.city,
state: req.body.state,
country
});
return address.save();
})
.then(address => res.send(address))
.catch(err => res.send(500, { message : 'Something went wrong', err }));