【问题标题】:Assign a result from promise to an external variable将 promise 的结果分配给外部变量
【发布时间】:2018-03-13 11:30:18
【问题描述】:

我正在使用 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。 我没有错误,它根本不会将国家/地区保存在地址中,因为承诺中的 newAddress 与代码开头声明的 newAddress 不同

【问题讨论】:

    标签: node.js mongodb mongoose promise


    【解决方案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 的内容以及如何从异步函数返回。

    【讨论】:

    • 感谢您的指出!我正在阅读很多关于 Promise 的内容,但我完全错过了这一点。代码真的更复杂,我正在尝试从回调更改为承诺
    【解决方案2】:
    1. 将地址创建移到承诺链中。
    2. 不要混合使用回调风格和承诺风格的代码(newAddress.save() 返回一个承诺)。
    3. 使用单个 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 }));
    

    【讨论】:

    • 我在前提之外对newAddress 进行了其他分配,这就是我在 findOne 函数之前声明 var newAddress 的原因。让我编辑问题以更好地澄清它
    • 你可以在then回调中做所有这些事情,检查更新的答案。
    • 我喜欢在then 回调中声明所有内容的方式,但它不起作用。对于city: req.body.city,它返回此错误SyntaxError: Invalid shorthand property initializer
    • req.body.cityreq.body.state 有哪些值?
    • 它们是字符串,来自表单提交。我将在问题中发布代码
    猜你喜欢
    • 2021-06-19
    • 2021-08-21
    • 2016-10-10
    • 2020-05-15
    • 2021-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多