[英]Get Async Dependency globally Inversify
我希望在頂層獲得異步依賴,而不必使用頂層等待。
目前,我通過在getService()
文件中聲明異步 function 來使用臨時 hack。 但是,通過這樣做,我必須為我在 controller 文件中聲明的每條路線調用getService()
function。
這是我當前的代碼:
// something.controller.ts
const router = Router();
async function getService() { // temporary hack
return await container.getAsync<IService>(TYPES.Service)
}
router.get("/collection",
paginateCollectionSchema,
validateRequestSchema,
async (req, res) => {
const service = await getService(); // if I have 100 routes, I have do this 100 times
const paginationSettings = await service.getSome(req.query.limit, req.query.offset);
const pagination = paginate("/collection", paginationSettings);
return res.json(pagination)
},
);
...
export router;
我希望實現的是這樣的:
// something.controller.ts
const router = Router();
// get service once without using top level await
router.get("/collection",
paginateCollectionSchema,
validateRequestSchema,
async (req, res) => {
// no need to get service
const paginationSettings = await service.getSome(req.query.limit, req.query.offset);
const pagination = paginate("/collection", paginationSettings);
return res.json(pagination)
},
);
...
export router;
如果您想在服務器運行之前完成一些異步初始化,以便您可以將該異步結果用作服務器 rest 中的常規變量,那么您可以進行該異步調用,然后直到結果可用。 然后,您可以將它放在一個變量中,並從任何服務器請求處理程序中將其作為常規變量引用。
如果您需要在其他模塊中使用該值,那么您可以創建一個同步的 getter function,您可以導出它來返回該變量(您不能直接導出它)。
僅供參考,這類問題正是發明頂級await
以使解決方案更簡單的原因。
您沒有顯示太多代碼結構,但這是總體思路:
// variable at top scope you can use in the rest of the code AFTER
// the server has been started
let mainService;
getService().then(service => {
mainService = service;
// don't start your server until you have the service available
app.listen(...);
}).catch(err => {
console.log("Failed to start server", err);
});
app.get((req, res) => {
// can use mainService variable directly here
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.