簡體   English   中英

異步功能在全局環境中不起作用

[英]Async function doesn't work in global environment

我在全局環境中創建了一組異步函數。 我想在所有模塊之間重用異步功能。 當我在其他模塊中調用重用異步函數時,它返回未定義。

全球

module.exports = ((global) => {
   return {
     async funcA(){
       return Promise.resolve();
     },
     async funcB(){
       return Promise.resolve();
     }
   }
})

終點

module.exports = ((global) => {
   return async(req, res, next) => {
     var getA = await global.funcA(); // Undefined
   };
});

路線

import global from './global';

console.log(global); // all the scripts
console.log(global.funcA); // Undefined

let endpoint = require('./endpoint')(global);


api.get('/test', endpoint);

首先,您不應該使用全局術語,因為Node.js已經使用了它。

無論如何,您似乎正在嘗試從名為global的文件中導出某些功能,然后可以在整個應用程序中導入和使用這些功能。


全球功能

您只需要返回一個承諾就不需要導出異步函數。 您也不需要將global作為參數的函數。

因此,您可以僅導出包含兩個函數的對象:

module.exports = {
  funcA() {
    return Promise.resolve('Value A')
  },
  funcB() {
    return Promise.resolve('Value B')
  }
}

終點

這是您在使用await關鍵字時想要異步功能的地方:

const globalFuncs = require('./global-funcs')

module.exports = async (req, res) => {
  let getA = await globalFuncs.funcA()

  // Send result as response (amend as necessary)
  res.send(getA)
}

路線

在這里,您只需導入端點函數並在路由中使用它:

const endpoint = require('./endpoint')

api.get('/test', endpoint)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM