【问题标题】:What is the correct way to export an Async function module?导出异步功能模块的正确方法是什么?
【发布时间】:2020-05-26 23:54:38
【问题描述】:

我有一个文件asyncAwait.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);

})();

这会记录“函数返回的字符串”。到控制台。

一切都好。

但是,如果我在asyncAwait.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;

然后在testing.js:

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

(async () => {

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

    console.log(test);

})();

这会记录undefined

为什么第二个例子中的函数调用返回 undefined?

【问题讨论】:

  • 你的 getData() 函数没有 return 任何东西。
  • getData 没有返回任何内容
  • console.log(data); 将记录数据,但 console.log(test); 将记录 undefined,因为 getData(url)undefined

标签: javascript node.js async-await axios


【解决方案1】:

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

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

【讨论】:

  • 感谢代码 sn-p - 但是,导出时仍返回 undefined
【解决方案2】:
module.exports.doStuff = doStuff;

我可以建议你:

module.exports=doStuff;

或者

exports.doStuff

也许但不确定您要达到的目标 替换

return(getData(url));

return(()=>{return getData(url)});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-24
    • 1970-01-01
    • 2020-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    相关资源
    最近更新 更多