简体   繁体   English

异步功能在全局环境中不起作用

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

I created sets of async functions in global environment. 我在全局环境中创建了一组异步函数。 I want to re-use the async functions across all the modules. 我想在所有模块之间重用异步功能。 When I call the re-use async function in other module, it returned undefined. 当我在其他模块中调用重用异步函数时,它返回未定义。

Global 全球

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

Endpoint 终点

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

Routes 路线

import global from './global';

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

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


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

Firstly, you should not use the term global as Node.js already uses this. 首先,您不应该使用全局术语,因为Node.js已经使用了它。

Anyhow, it looks like you are trying to export some functions from a file called global which you can then import and use across your application. 无论如何,您似乎正在尝试从名为global的文件中导出某些功能,然后可以在整个应用程序中导入和使用这些功能。


GlobalFuncs 全球功能

You don't need to export async functions as you are just returning a promise. 您只需要返回一个承诺就不需要导出异步函数。 You also don't need a function taking global as an argument. 您也不需要将global作为参数的函数。

So you can just export an object containing the two functions: 因此,您可以仅导出包含两个函数的对象:

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

Endpoint 终点

This is where you want an async function as you are using the await keyword: 这是您在使用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)
}

Routes 路线

Here you can just import your endpoint function and use it in your routes: 在这里,您只需导入端点函数并在路由中使用它:

const endpoint = require('./endpoint')

api.get('/test', endpoint)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM