【问题标题】:How to export a variable inside self-invoking async function如何在自调用异步函数中导出变量
【发布时间】:2021-04-20 19:00:01
【问题描述】:

我有一个自调用async function,在运行文件后应该导出一个variable,其中包含stringsarray 和一堆URLs,然后它将被导入到另一个文件中之后我会跑。

这是我的代码:

// file1.js
(async () => {
  // bunch of irrelevant code here

  // gets all URLs, formatted & store in this variable
  const availableFormattedUrls = formatUrls(allUrls); // I get all URLs here - array of strings

  module.exports = { availableFormattedUrls }; 
})();

然后我尝试将variable 导出到另一个文件并像这样打印它:

// file2.js
const { availableFormattedUrls } = require('./file1.js');
console.log(availableFormattedUrls); // I get undefined here

我通过终端运行这些文件,如下所示:node file1.js && file2.js,但我在第二个文件中不断收到undefined

我也试过这样:

// file1.js
module.export = (async () => {
  ....
  ....

  return availableFormattedUrl; 
})();

但同样,它不起作用。发生了什么事?

【问题讨论】:

  • 考虑Asynchronous nodejs module exportsHow to export an object returned by async/await method。基本上你不能在事后添加额外的导出。您的第二次尝试更合理,因为现在您正在导出应解析为所需 url 值的承诺。当你这样尝试时,它“不起作用”怎么办?
  • @CRice 感谢您的回复。第二次尝试也让我undefined。我不知道为什么?
  • 在考虑了一秒钟之后...您正在导出异步函数的返回,这意味着导出的值 必须 是某种 Promise。该导出甚至不可能是undefined。你能展示你是如何使用出口的吗?也许问题出在消费者方面。
  • 如果您要导出承诺,则必须使用 await require('./file1.js')require('./file1.js').then(…)
  • "我正在通过终端运行这些文件,如下所示:node file1.js && file2.js" - 呃,不要。那是使用 bash 语法运行两个单独的脚本,第二个是可能带有 shebang 的可执行文件?相反,编写一个程序(由多个模块组成)并只运行它。

标签: javascript node.js module async-await


【解决方案1】:

我能够像这样导出它:

module.export = (async () => {
  ....
  ....

  return availableFormattedUrl; 
})();

然后,像这样导入它:

const availableFormattedUrls = require('./file1.js');

最后,我可以使用命令node file2.js 运行它

【讨论】:

    【解决方案2】:

    我看到一个错误:

    在 file2.js 中你需要错误的文件 require('./fetch-urls');

    代替:

    const { availableFormattedUrls } = require('./file1.js');
    

    并且您需要确保:

    formatUrls(allUrls) 没有返回 undefined

    【讨论】:

    • 这是我编辑代码时犯的错误
    猜你喜欢
    • 2020-09-30
    • 2022-11-26
    • 2020-03-09
    • 2017-09-28
    • 2020-12-20
    • 2020-10-17
    • 2016-12-28
    • 1970-01-01
    • 2022-11-14
    相关资源
    最近更新 更多