Javascript 异步函数不';我们不能在全球环境中工作

Javascript 异步函数不';我们不能在全球环境中工作,javascript,node.js,express,es6-promise,es6-modules,Javascript,Node.js,Express,Es6 Promise,Es6 Modules,我在全局环境中创建了异步函数集。我想在所有模块中重复使用异步函数。当我在其他模块中调用重用异步函数时,它返回undefined 全球 module.exports = ((global) => { return { async funcA(){ return Promise.resolve(); }, async funcB(){ return Promise.resolve(); } } }) 终点 mod

我在全局环境中创建了异步函数集。我想在所有模块中重复使用异步函数。当我在其他模块中调用重用异步函数时,它返回undefined

全球

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);

首先,您不应该使用术语global,因为Node.js已经使用了这个术语

无论如何,看起来您正试图从名为global的文件中导出一些函数,然后可以在整个应用程序中导入和使用这些函数


全球基金会

import global from './global';

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

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


api.get('/test', endpoint);
您不需要导出异步函数,因为您只是返回一个承诺。您也不需要将全局作为参数的函数

因此,您可以只导出包含两个函数的对象:

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

终点

module.exports = ((global) => {
   return async(req, res, next) => {
     var getA = await global.funcA(); // Undefined
   };
});
当您使用await关键字时,这里需要一个async函数:

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)
}

路线

import global from './global';

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

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


api.get('/test', endpoint);
在这里,您可以导入端点函数并在路由中使用它:

const endpoint = require('./endpoint')

api.get('/test', endpoint)
首先,阅读本文并决定是创建异步函数还是使用异步函数。