0

I am working with express server and trying to read data from file and return it to different function.

My code structure looks like this:

async function getUser(req) { 
   fs.readFile(cfg.fileDefaults, (err, defaults) => {
      do something
      return user;
    }
}

module.exports = {getUser}

In controller I call that function

  static getTable(req, res, next) {
    async function search() {
      user = await  getUser(req);  //return undefined
     getUser(req).then((a) => {
           console.log(a);       //second try, return undefined
          })
    }
    search();
}

How should I call it correctly?

13Akaren
  • 225
  • 3
  • 16
  • 1
    `getUser` doesn't return anything; I'm not sure what you're expecting. Please see [How do I return the response from an aynchronous call](https://stackoverflow.com/q/14220321/438992), which this duplicates. – Dave Newton Oct 22 '20 at 13:34

1 Answers1

1
const fs = require('fs')
function getUser(req) {
  return new Promise((resolve, reject) => {
    fs.readFile(cfg.fileDefaults, (err, defaults) => {
      //do something
      const user = { hellow: 'world' }
      resolve(user)
    })
  })
}
module.exports = { getUser }

In controller

static getTable(req, res, next) {
    async function search() {
      user = await getUser(req); // return { hellow: 'world' }
      res.end(JSON.stringify(user, null, '  '))
    }
    search().catch((err) => {
      console.log('err',err)
      res.status(500)
      res.end('error')
    })
}