美文网首页
promise与async 数据库查询封装对比

promise与async 数据库查询封装对比

作者: Wrestle_Mania | 来源:发表于2019-11-29 23:13 被阅读0次
    • async await
    const Config = require("./config");
    
    const MongoClient = require("mongodb").MongoClient;
    
    const client = new MongoClient(Config.dbUrl, { useUnifiedTopology: true });
    
    class Db {
      constructor() {
        // this.connect();
      }
      async connect() {
        try {
          await client.connect();
          return client.db(Config.dbName);
        } catch (e) {
          throw new Error(e);
        }
      }
      async find(collectionName, json) {
        try {
          const db = await this.connect();
          const collection = db.collection(collectionName);
          const docs = await collection.find(json).toArray();
          return docs;
        } catch (e) {
          throw new Error(e);
        }
      }
    }
    
    const db = new Db();
    
    (async () => {
      try {
        const docs = await db.find("student", {});
        console.log(docs);
      } catch (e) {
        console.log(e.message);
      }
    })();
    
    • promise
    const Config = require("./config");
    
    const MongoClient = require("mongodb").MongoClient;
    
    const client = new MongoClient(Config.dbUrl, { useUnifiedTopology: true });
    
    class Db {
      constructor() {
        // this.connect();
      }
      connect() {
        return new Promise((resolve, reject) => {
          client.connect(err => {
            if (err) {
              reject(err);
            } else {
              const db = client.db(Config.dbName);
              resolve(db);
            }
          });
        });
      }
      find(collectionName, json) {
        return new Promise((resolve, reject) => {
          this.connect()
            .then(db => {
              const collection = db.collection(collectionName);
              collection.find(json).toArray((err, docs) => {
                if (err) {
                  reject(err);
                } else {
                  resolve(docs);
                }
              });
            })
            .catch(e => {
              reject(e)
            });
        });
      }
    }
    
    const db = new Db();
    
    db.find("student", {})
      .then(docs => {
        console.log(docs);
      })
      .catch(e => {
        console.log(e.message);
      });
    

    相关文章

      网友评论

          本文标题:promise与async 数据库查询封装对比

          本文链接:https://www.haomeiwen.com/subject/rmenwctx.html