Mongodb + Node:什么时候closures

我正在研究Koa + Mongodb后端。 我的问题是:什么时候应该closures数据库,还是Mongodbpipe理,因为我现在没有closures它们中的任何一个,似乎很好。

// app.js const Koa = require('koa') const database = require('./database') const app = new Koa() database .connet() .then(() => {app.listen(':8080')}) .catch((err) => {console.error(err)}) // ./database.js const MongoClient = require('mongodb').MongoClient const Model = require('./model') class Database { async connect() { if (!db) { db = await MongoClient.connect("localhost:27017") this.item = new Model(db, 'item_collection') } } } module.exports = new Database() // ./model.js class Model { constructor(db, collectionName) { this.name = collectionName this.database = database } async findAll() { const result = await this.db.collection(this.name).find().toArray() if (!result) { throw new Error('error') } return result } } module.exports = Model 

我还使用vegeta进行了压力testing,以100次/秒的速度向服务器发出API请求,响应时间很好。 那么,我担心这里的过早优化吗? 如果没有,我应该什么时候closures数据库?

当Koa继续运行(并在你的情况下监听端口8080),你不应该closures数据库连接。

如果您正在运行预计将结束的脚本(在cron上运行的任务等),则应在完成所有数据库任务时手动closures连接。

你可以看看这个例子 express.js(Koa的姊妹框架)