Javascript 导出异步功能模块的正确方法是什么?

Javascript 导出异步功能模块的正确方法是什么?,javascript,node.js,async-await,axios,Javascript,Node.js,Async Await,Axios,我有一个文件asyncwait.js,它有一个简单的函数: async function doStuff() { return(`Function returned string.`); } module.exports.doStuff = doStuff; 在另一个模块中,testing.js,我调用并按预期工作: var functions = require(`./functions`); (async () => { const test = await f

我有一个文件
asyncwait.js
,它有一个简单的函数:

async function doStuff() {
    return(`Function returned string.`);
}

module.exports.doStuff = doStuff;
在另一个模块中,
testing.js
,我调用并按预期工作:

var functions = require(`./functions`);

(async () => {

    const test = await functions.asyncAwait.doStuff();

    console.log(test);

})();
此操作将“函数返回字符串”记录到控制台

一切都好

但是,如果我在
asyncwait.js
中使用axios:

const axios = require(`axios`);

async function doStuff(parameter) {

    const url = `https://jsonplaceholder.typicode.com/posts/1`;

    const getData = async url => {
        try {
            const response = await axios.get(url);
            const data = response.data;
            console.log(data);
        } catch (error) {
            console.log(error);
        }
    };

    return(getData(url));
}

module.exports.doStuff = doStuff;
var functions = require(`./functions`);

(async () => {

    const test = await functions.asyncAwait.doStuff();

    console.log(test);

})();
然后在
testing.js
中:

const axios = require(`axios`);

async function doStuff(parameter) {

    const url = `https://jsonplaceholder.typicode.com/posts/1`;

    const getData = async url => {
        try {
            const response = await axios.get(url);
            const data = response.data;
            console.log(data);
        } catch (error) {
            console.log(error);
        }
    };

    return(getData(url));
}

module.exports.doStuff = doStuff;
var functions = require(`./functions`);

(async () => {

    const test = await functions.asyncAwait.doStuff();

    console.log(test);

})();
此日志记录未定义的


为什么在第二个示例中函数调用返回undefined

在您的示例中,
getData
没有返回值。在这种情况下,函数将隐式返回
undefined
。要修复它,您可以将该函数更改为以下内容:

    const getData = async url => {
    try {
        const response = await axios.get(url);
        return response.data;
    } catch (error) {
        return error
    }
};
我可以建议你:

module.exports=doStuff;

也许,但不确定你想要实现什么 替换


您的
getData()
函数不会
返回任何内容。
getData
不会返回任何内容
console.log(数据)
将记录数据,但
console.log(测试)
将记录
undefined
,因为
getData(url)
undefined
谢谢您的代码片段-但是,在导出时仍然返回
undefined
return(getData(url));
return(()=>{return getData(url)});