mongoDB承诺过早归还

mongoDB承诺过早归还,第1张

mongoDB承诺过早归还

它是预期的行为,它在仍处于挂起状态时会返回承诺。

您应该使用它

then()
来检查承诺解决方案。

另一件事是,在开始使用Promise时,您不应使用传统的mongo接口,而应承诺

Collection
原型的所有方法,因此您可以返回mongo
find方法及其可扩展链创建的Promise。否则,我看不到使用诺言的意义。您的方式不会减少您必须编写的代码量。

顺便说一句,恕我直言,您应该使用bluebird而不是Q,因为它是目前唯一不会非常慢的promise库。

范例:

在db.js中

var mongoClient = require('mongodb').MongoClient;var collection  = require('mongodb').Collection;var Promise     = require('bluebird');// We promisify everything. Bluebird add ***Async function which return promises.Promise.promisifyAll(collection.prototype);Promise.promisifyAll(mongoClient);//In mongodb cursor is not built from protoype I use to promisify it each time. Not necessary if you don't use cursors.collection.prototype._find = collection.prototype.find;collection.prototype.find = function() {  var cursor = this._find.apply(this, arguments);  cursor.toArrayAsync = Promise.promisify(cursor.toArray, cursor); return cursor;};//then you connect to the DB and exports your collections...

在其他地方,以您的示例为例:

this.loginUser = function(user) {  var userid = user.userid,  var password = (user.password) ?    crypto.createHash("md5").update(user.password).digest("hex"):    undefined  var rememberme = user.rememberme;  if(userid && password) {    // we directly return the promise from mongodb, that we chain with a then    return db.users.findoneAsync({ email: userid, password: password }) // return a promise that we chain    .then(function(user) { // that we chain      if(user) {        var loginpre = uuid.v4(),        var token = jwt.enpre({email: userid, password: password}, secret);        if(rememberme) {          res.cookie("cloginpre", loginpre, { magAge: 900000 } );        }        return user;  // return in a then callback will just resolve the promise      } else {        throw  new Error('User not found'); // throwing in a then callback will just reject the promise      }    }); // end of the then, then return a promise that we return (with the return keyword above)  } else {    return Promise.reject("Username or Password was not entered"); // this is the only case where we have to actually create a promise ourself  }}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/zaji/5088045.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-16
下一篇2022-11-16

发表评论

登录后才能评论

评论列表(0条)

    保存