koa2 的 await-async 結合 mongoose 的使用

koa2 在koa1 基礎上提供了一種更好的異步流程控制方案--await-async,await-async能夠讓異步邏輯用同步寫法實現,以下面的例子:html

function getSyncTime() {
  return new Promise((resolve, reject) => {
    try {
      let startTime = new Date().getTime()
      setTimeout(() => {
        let endTime = new Date().getTime()
        let data = endTime - startTime
        resolve( data )
      }, 500)
    } catch ( err ) {
      reject( err )
    }
  })
}

async function getSyncData() {
  let time = await getSyncTime()
  let data = `endTime - startTime = ${time}`
  return data
}

async function getData() {
  let data = await getSyncData()
  console.log( data )
}

getData()

該方案的關鍵詞是 await 和 async,須要注意的是 最底層的 await 調用函數必須返回一個Promise對象,例如get SyncTime() 必須返回一個Promise對象。git

下面介紹 koa2 與 mongoose 的結合,實現查詢功能。github

var mongodb = require('../config.js');
var Schema = mongodb.mongoose.Schema;

/**
 *  schema
 **/
var departmentSchema = new Schema({
    id: String, //部門編號
    name: String //名稱
});


/**
 *  schemao
 **/
var employeeSchema = new Schema({
    id: Number, //工號
    name: String, //姓名
    sex: Number, //性別
    age: Number, //年齡
    // dep_id: String //部門
    dep: {
        type: Schema.Types.ObjectId,
        ref: 'department'
    }
});


// Instances of Models are documents. 
// Documents have many of their own built-in instance methods. 
// We may also define our own custom document instance methods too.
// NOTE: methods must be added to the schema before compiling it with mongoose.model()
employeeSchema.methods.printInfo = function() {
    var greeting = this.name;
    console.log("Testing methods defined in schema:" + greeting);
}

/**
 *  model
 **/
var employee = mongodb.mongoose.model("employee", employeeSchema);
var department = mongodb.mongoose.model('department', departmentSchema);

var employeeDAO = function() {};

//We can access all of the employee documents through our employee model.
employeeDAO.prototype.findAll = async function(callback) {
    let list = await employee.find({}).populate({ path: 'dep', select: { name: 1 } }).exec(); 
    return list
}

module.exports = new employeeDAO();

在上述代碼中,定義了schema、model,並提供了一個數據庫查詢 DAO 對象。因爲 mongoose 的保存、查詢等異步操做返回的是Promise對象結果,因此直接能夠經過 await 方法調用 mongooseAPI,如mongodb

await employee.find({}).populate({ path: 'dep', select: { name: 1 } }).exec();

mongoose API 可參考這裏數據庫

下面經過調用DAO實現查詢功能:segmentfault

const Router = require('koa-router')

let employee = require('./../models/employee.js');
let employeeList = new Router()


employeeList.get('/', async(ctx) => {
    var result = await employee.findAll();
    await ctx.render('list', {
        employeeList: result
    })
})

module.exports = employeeList;

須要注意的是,因爲 DAO 中的 findAll 函數內部經過 await 調用了一個異步查詢,因此 findAll 函數須要用 async 關鍵詞聲明。promise

本demo源碼可參考這裏koa

Express 結合 mongoose 的使用請參考我以前的文章異步

相關文章
相關標籤/搜索