Promise是一种异步编程的代码书写方式,和Async模块一样,都能提高代码的可读性和可维护性。Async封装的比Promise要好,但是灵活性特别是彻底的去CallBack化会比Promise要差一点。下面直接贴下源代码,注释很详细:
(1)数据库连接文件:dbConfig
/** * Created by apple on 2014/12/29. */ var mongoskin = require(‘mongoskin‘); var db = null; var dbName = "yqbChat"; /** * @function * @param collectionName * @returns {SkinCollection|null|*} */ exports.getCollection = function (collectionName) { if (!db) { //连接本机mongodb ,使用帐号密码连接 mongoskin.db(‘username:[email protected]服务器ip/数据库名 db = mongoskin.db(‘mongodb://127.0.0.1:27017/‘ + dbName + ‘?auto_reconnect=true&poolSize=3‘, {numberOfRetries: 1, retryMiliSeconds: 500, safe: true, native_parser: true}, {socketOptions: {timeout: 5000}} ); } return db.collection(collectionName); }; /** * @function 关闭数据库 */ exports.dbClose = function() { if (!db) { db.close(); } };
(2)Model 层文件
/** * Created by apple on 2015/1/17. */ /** 聊天室数据结构 * * //某两个用户对应的聊天室为一个集合,一个消息为一个文档 * @{singleChatRoomID} * @_id 信息编号 * @msgState 0-未读 1-已读 (int类型) * @msgContent 消息内容 * @msgSend 消息发送者的user_id * @create_time * */ //获取MongoDB的连接实例 var moment = require(‘moment‘); var Q = require("q"); //存放聊天室配置集合 var singleChatRoomConfigInstance = null; //当前时间点 var currentDateTime = moment().format("YYYY-M-D H:m:s"); /** * @function 根据singleChatRoomID在singleChatRoomConfig文档中搜索配置信息 * @param singleChatRoomID 聊天室ID * @param callback 回调函数 如果为promise为空 * @param promise 如果存在promise,则callback为空 */ exports.findSingleChatRoomByID = function (data) { //根据singleChatRoomID搜索对应聊天室的配置,如果存在则返回聊天室配置,否则返回false if (singleChatRoomConfigInstance == null) { singleChatRoomConfigInstance = data.db.getCollection(‘singleChatRoomConfig‘); } var deferred = Q.defer(); console.log("[SingleChatRoomConfig->findSingleChatRoomByID]:开始根据聊天室ID查找配置数据!"); //查询 singleChatRoomConfigInstance.findOne({singleChatRoomID: data.singleChatRoomID}, function (error, result) { if (typeof data.promise != undefined) { if (!error) { data.result = result; //console.log(data); deferred.resolve(data); } else { deferred.reject(error); } } else { callback(error, data); } //db.dbClose(); }); return deferred.promise; }; /** * @function 在聊天室配置集合中插入新的集合 * @param singleChatRoomID * @param user_id_1 * @param user_id_2 * @param callback * @param promise */ exports.insertSingleChatRoomByID = function (data) { //根据singleChatRoomID搜索对应聊天室的配置,如果存在则返回聊天室配置,否则返回false if (singleChatRoomConfigInstance == null) { singleChatRoomConfigInstance = data.db.getCollection(‘singleChatRoomConfig‘); } var deferred = Q.defer(); console.log("[SingleChatRoomConfig->insertSingleChatRoomByID]:开始插入数据!"); //console.log(data); singleChatRoomConfigInstance.insert( { singleChatRoomID: data.singleChatRoomID, users: [data.user_id_1, data.user_id_2], msgCount: 0, createTime: currentDateTime }, function (error, result) { if (typeof data.promise != undefined) { if (!error) { data.result = result; deferred.resolve(data); } else { deferred.reject(error); } //db.dbClose(); } else { callback(error, result); //db.dbClose(); } } ); return deferred.promise; };
(3)Test文件
/** * Created by apple on 2015/1/17. */ var singleRoomConfigModel = require(‘../SingleRoomConfigModel‘); var model = require(‘../Model‘); var db = require(‘../db/dbConfig‘); var Q = require("q"); /** * @function 测试在singleChatRoomConfig中查询是否存在某个聊天室的配置记录,不存在则创建 * @param singleChatRoomID */ /**CallBack风格的函数*/ function testFindAndInsertByID_CALLBACK(singleChatRoomID) { //执行查询操作的回调函数 this.findSingleChatRoomByIDCallBack = function (error, result) { console.dir("findSingleChatRoomByIDCallBack invoked!" + result); //如果结果不为空,则查询所有未读信息 if (result != null) { } else //如果结果为空,则建立一条新的数据返回未读信息条数为空 { singleRoomConfigModel.insertSingleChatRoomByID(singleChatRoomID, 1, 2, this.insertSingleChatRoomByIDCallBack); } }; //执行插入操作的回调函数 this.insertSingleChatRoomByIDCallBack = function (error, result) { if (error != null) { console.log(result); } else { console.error(error); } }; singleRoomConfigModel.findSingleChatRoomByID(singleChatRoomID, this.findSingleChatRoomByIDCallBack); } /**Promise风格的函数*/ function testFindAndInsertByID_PROMISE(singleChatRoomID) { var data = { singleChatRoomID: singleChatRoomID, promise: true, db:db }; singleRoomConfigModel.findSingleChatRoomByID(data).then( /** * @function 逻辑判断层,聊天室存在则返回聊天室信息,否则进入聊天室创建 * @param result */ function (data) { var deferred = Q.defer(); if(data) { //console.log("聊天室存在,输出聊天室配置!"); deferred.resolve(data); } else{ //console.log("聊天室不存在,开始创建聊天室!"); //继续设置下一层的promise调用 deferred.reject(data); } return deferred.promise; } , model.errorHandler ).then( function(data){ //console.log("获取到了聊天室配置!"); var deferred = Q.defer(); deferred.resolve(data); return deferred.promise; }, singleRoomConfigModel.insertSingleChatRoomByID ).done( function(data){ //console.log("testFindAndInsertByID_PROMISE-完毕"); //console.log(data); data.db.dbClose() }, model.errorHandler ); } testFindAndInsertByID_PROMISE("1");
时间: 2024-10-11 01:32:21