Search code examples
node.jsmoduleasync-awaitexportrequire

Exporting and requiring an async function error


I export an async function in a file called resourcess.js like this:

//resourcess.js
module.exports = function(arg) {
    let do_stuff = async (arg) => {
    ...
}

Then i require that file in routes.js like this:

let importedFunc = require('./resourcess.js');

Finally i use it in routes.js like this:

app.post('/post', function(req, res) {
        var a2 = req.body.a1;
        importedFunc(a2).then(result => {
            console.log(result);
        res.render('index.ejs');
        }).catch(err => {
            console.log(err);
            res.render('index.ejs');
        })
    });

This is the error message i get:

TypeError: Cannot read property 'then' of undefined

I cannot understand what i am doing wrong....


Solution

  • If you're not calling do_stuff and returning the promise, then the exported function isn't actually returning a promise:

    //resourcess.js
    module.exports = function(arg) {
        let do_stuff = async (arg) => {
          // something should be done inside this function
          let data = await somethingThatReturnsData(arg);
          return data;
        };
        return do_stuff(arg);
    }
    

    But from how this is being used, I think you want to do the following:

    //resourcess.js
    // see that async is on the actual exported function
    module.exports = async function(arg) {
      let data = await somethingThatReturnsData(arg);
      // do stuff to data
      return data;
    };