将promise的结果分配给外部变量

时间:2017-10-02 11:39:21

标签: node.js mongodb mongoose promise

我正在使用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不同

2 个答案:

答案 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)

  1. 将地址创建移至承诺链中。
  2. 不要混合使用回调式和承诺式代码(newAddress.save()返回承诺)。
  3. 使用单catch处理程序处理所有可能的错误。
  4. 代码:

    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 }));