栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

mongoDB承诺过早归还

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/427135.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号