导出并要求异步功能错误

时间:2018-08-08 13:59:34

标签: node.js module async-await export require

我将异步函数导出到名为resourcess.js的文件中,如下所示:

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

然后我需要在route.js中添加该文件,如下所示:

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

最后,我在如下的routes.js中使用它:

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

这是我收到的错误消息:

TypeError: Cannot read property 'then' of undefined

我不明白我在做什么错....

3 个答案:

答案 0 :(得分:2)

如果您没有调用do_stuff并返回承诺,则导出的函数实际上并没有返回承诺:

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

但是从如何使用来看,我认为您想执行以下操作:

//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;
};

答案 1 :(得分:2)

您的resourcess.js文件是包装异步函数的函数。

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

您没有先调用导入的函数,因此其中的异步函数尚不存在。

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

要更正它,只需将其重写为importedFunc()(a2).then

如果您想像现在一样使用它,请像这样重做resourcess.js实现:

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

//resourcess.js
module.exports = async arg => {
    ...
}

...是do_stuff函数中的代码。

答案 2 :(得分:0)

如果您要使用async/await,请坚持使用,并尽量不要将其与承诺混淆。

app.post('/post', async function(req, res) {
    try {
        var a2 = req.body.a1;
        var result = await resimportedFunc(a2);
        console.log(result);
        res.render('index.ejs');
    } catch(err){
        console.log(err);
        res.render('index.ejs');
    }
});