是否可以从异步函数中 module.exports 一个局部变量? [英] Is it possible to module.exports a local variable from async function?

查看:67
本文介绍了是否可以从异步函数中 module.exports 一个局部变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个名为 index.main.js 的文件中有这个异步函数,它有一个变量targetFiles",我想将它导出到另一个文件 index.js.问题是我无法找到一种方法来导出此特定变量的值而不会导致未定义".

I have this async function in a file called index.main.js which has a variable , 'targetFiles' which I would like to export to another file which is index.js. Problem is I can't find a way to export the value of this particular variable without getting "undefined" as a result.

我尝试过实现 promise、callback、export default 函数,并做了无数小时的研究,但无济于事.

I have tried implementing promise, callback , export default function, and doing countless hours of research to no avail.

 //this code is in index.main.js

  var targetFiles = "";

  async function listFilesInDepth()

    {

      const {Storage} = require('@google-cloud/storage');

      const storage = new Storage();

      const bucketName = 'probizmy';

      const [files] = await storage.bucket(bucketName).getFiles();

      console.log('List Of Files Available:'); 



        files.forEach(file =>

          {

            targetFiles = file.name;  //this is the variable to export

            console.log(`-----`+file.name);

          });

         return targetFiles;

    }


  module.exports = {
   fn : targetFiles
  }

试图将值导出到 index.js 为空或未定义"

trying to export the value to index.js is either empty or "undefined"

   //this is the code in index.js
   const a = require('./index.main');
   console.log(a.fn); //undefined or empty

应该是输出的预期值是 targetFiles 的值.假设 targetFiles 是 async 函数中的 abc12345.JSON,那么 index.js 中的 console.log 应该是那个值.

The expected value that should be the output is the value of targetFiles. Let's say if targetFiles is abc12345.JSON in the async function,the console.log in index.js should be of that value.

我希望有人能给我一些有关如何克服这个问题的见解.提前谢谢你:)

I'm hoping someone could give me some insight on how I could overcome this issue. Thank you in advance :)

推荐答案

以下解决方案可能对您有所帮助,但不确定是否适合您的用例.(不使用 module-exports):

Following solution might help you, but not sure for your use case. (Not using module-exports):

您可以使用 request-context package 来实现相同的功能.

You can use request-context package to achieve same functionality.

包的作用是,您可以针对 key 设置 value(data),然后在同一 中的以下代码执行中访问相同的内容上下文.

What is package does is, you can set the value(data) against a key and then access the same in the following code execution within the same context.

运行 npm install request-context

在您的主 app.js(服务器文件)中,将 request-context 注册为中间件.

In your main app.js (server file), register the request-context as a middleware.

const contextService = require("request-context");
const app = express();
...
// Multiple contexts are supported, but below we are setting for per request.
app.use(contextService.middleware("request"));
...

然后在您的 index.main.js 中,一旦 targetFiles 准备就绪,将 targetFiles 设置为请求上下文.

And then in your index.main.js, once targetFiles is ready, set the targetFiles into request context.

const contextService = require("request-context");

...
files.forEach(file =>

      {

        targetFiles = file.name;  //this is the variable to export

        console.log(`-----`+file.name);

      });
     // Here `Request` is the namespace(context), targetFileKey is the key and targetFiles is the value.
     contextService.set("request:targetFileKey", targetFiles);
     return targetFiles;

}
...

在同一个请求中,如果您想使用 targetFile,您可以执行以下操作:

And in the same request, where you wanna use targetFile, you can do the following:

index.js (可以是设置后需要targetFiles的任何文件):

index.js (Can be any file where you need targetFiles after being set):

const contextService = require("request-context");

...
// Reading from same namespace request to which we had set earlier
const targetFiles = contextService.get("request:targetFileKey");
...

请注意:您将能够在您设置的同一 request 中访问 targetFiles.这意味着,我们在app.js中配置的request-context是针对每个API请求的,也就是说,在每个API请求中,你必须在阅读之前设置它.

Please note: You will be able to access targetFiles in the same request you set. That means, request-context we configured in app.js is per API request, meaning, in every API request, you have to set it before reading.

如果上述解决方案不适合您,请告诉我.

Please let me know if the above solution doesn't fit for you.

这篇关于是否可以从异步函数中 module.exports 一个局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆