如何在自调用异步函数中导出变量



我有一个自调用的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; 
})();

但是,它还是不起作用。发生什么事情了?

我可以像这样导出它:

module.export = (async () => {
....
....
return availableFormattedUrl; 
})();

然后,像这样导入:

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

最后,我可以用命令node file2.js

运行它

我看到一个错误:

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

代替:

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

你需要确保:

formatUrls(allUrls)没有返回undefined

最新更新