[英]exporting multiple functions but always run default function first
抱歉,描述不當,但我想創建一個“service.js”文件,在其中導出多個從數據庫中檢索數據的函數。 就像是:
...
import Person from '../models/Person'
import dbConnect from "../lib/dbConnect";
await dbConnect()
const save = async (person) => {
const savedPerson = await Person.save(person)
return savedPerson
}
const geAll = async () => {
const persons = await Person.find({})
return persons
}
...
export default { getAll, save };
但是,在代碼中使用導出的函數時,我如何始終運行 dbConnect()? 我需要將 await dbConnect() 添加到每個函數中還是有一些更聰明的方法來做到這一點?
構造函數上帶有await dbConnect()
的類怎么樣? 就像是:
class MyClass {
constructor() {
return (async () => {
await dbConnect();
return this; // new instance created
})();
}
async save(person) {
const savedPerson = await Person.save(person)
return savedPerson
}
async geAll() {
const persons = await Person.find({})
return persons
}
}
然后:
const myClass = await new MyClass(); // <-- this calls dbConnect()
myClass.geAll();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.