-1

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);
Abel
  • 1,494
  • 3
  • 21
  • 32
  • First of all read this [link](https://stackoverflow.com/a/6898978/3030495) and decide to do you want to create an async function or use async function. – hurricane Nov 09 '17 at 07:20

1 Answers1

2

Firstly, you should not use the term global as Node.js already uses this.

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.


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.

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:

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)
Steve Holgado
  • 11,508
  • 3
  • 24
  • 32