简体   繁体   English

在猫鼬中使用Promise的最佳实践

[英]Best Practice of using Promise with Mongoose

I'm quite new with this promise concept. 我对这个诺言概念很陌生。 I'm not sure but looking at this, I belieave I'm just using promise as callbacks and I'm ending in a promise hell! 我不确定,但是看着这个,我相信我只是将promise用作回调,而我以promise地狱结束!

I've this function which is suppose to get user object from MongoUser database, update it and save it again. 我有这个功能,它想从MongoUser数据库中获取用户对象,对其进行更新并再次保存。 here's my code snippet: 这是我的代码段:

var changePassword = function(data){
      return new Promise(function(fulfill, reject){
        MongoUser.findOne({username: data.username}).exec()
          .then(function(mongoUser){
            //mongoUser = new MongoUser();
            //mongoUser.username = data.username;
            mongoUser.password = data.password;
            mongoUser.save().then(function(){
              fulfill(data);
            }).catch(function(error){
              log.error("MongoDB Failed in updating data", {"error": error});
              reject(error);
            });
          })
          .catch(function(error){
            log.error("MongoDB Failed in updating data", {"error": error});
            reject(error);
          });
      });
};

Any Idea how to use returned promise from Mongoose without creating a new one? 任何想法如何使用猫鼬返回的诺言而不创建新的诺言?

Mongoose supports promises already, so I think that you can rewrite your code to this: 猫鼬已经支持诺言 ,所以我认为您可以将代码重写为:

var changePassword = function(data) {
  return MongoUser.findOne({username: data.username}).then(function(mongoUser) {
    mongoUser = new MongoUser();
    mongoUser.username = data.username;
    mongoUser.password = data.password;
    return mongoUser.save();
  }).catch(function(error){
    log.error("MongoDB Failed in updating data", {"error": error});
    throw error;
  });
};

(although I'm not sure why you are creating a user that may already exists). (尽管我不确定您为什么要创建可能已经存在的用户)。

Rightly Said: Mongoose supports promises already. 正确地说:猫鼬已经支持诺言 Also, I don't think so you need to create a new user with new credential instead you need to change password of current user. 另外,我不认为您需要使用新凭据创建新用户,而需要更改当前用户的密码。 Also I have returned the data while calling "changePassword" function. 另外,我在调用“ changePassword”函数时返回了数据。

var changePassword = function(data){
  return MongoUser.findOne({username: data.username}).exec()
      .then(function(mongoUser){
        mongoUser.username = data.username;
        mongoUser.password = data.password;
         return mongoUser.save();
      })
     .then(function(newSavedData) {
                return newSavedData; // returns the new saved data
      })
     .catch(function(error){
          log.error("MongoDB Failed in updating data", {"error": error});
          reject(error);
      });
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM