【问题标题】:How can I export a variable after initializing once?初始化一次后如何导出变量?
【发布时间】:2021-02-18 16:07:39
【问题描述】:

我有一个 api 调用设置来在我的快速服务器启动时检索我需要的一些数据,我想通过导入来跨多个文件重用这些数据。基本上使它成为一个全球性的,但只能通过导入/导出访问。

更新:我只想让getCreds api 调用一次,因为它们不会更改然后在我的应用程序中引用凭据。

不过,我不确定最好的方法。 :/

file1.js、file2.js 等等……

import creds from './libs/creds.js'

...use creds for something...

libs/creds.js

// not sure how to set creds once and export it

let creds;

const getCreds = async () => {
  ...api call to get creds, but do not want to call repeatedly...
  creds = api.data
}

export { creds };

【问题讨论】:

    标签: javascript node.js ecmascript-6


    【解决方案1】:

    我会尝试这样做

    let creds;
    
    const getCreds = () => {
      ...api call to get creds, but do not want to call repeatedly...
      creds = api.data
    }
    
    getCreds();
    
    export { creds };
    

    在任何地方导入它,它应该被调用一次。

    【讨论】:

      【解决方案2】:

      我不知道是否有更好的方法,但我所做的就是导出一个 getter 函数:

      let _creds;
      
      const getCreds = async () => {
        ...api call to get creds, but do not want to call repeatedly...
        _creds = api.data
      }
      
      function creds() {
          return _creds;
      }
      
      export { creds };
      

      这样每次调用 creds() 时都会得到 _creds 的更新值

      您甚至可以将 API 调用放入 creds getter 函数中,然后像这样缓存它:

      let _creds;
      
      export function credsGetter() {
          if (_creds) {
             return _creds;
          } else {
              ...do the API call
              _creds = response.data
              return response.data;
          }
      }
      

      然后你可以像这样导入它:

      import { credsGetter } from "someFile";
      
      const creds = credsGetter();
      

      您不必担心 API 会被多次调用,因为它会缓存值:)

      无论如何,我不知道是否有更好的解决方案,我也一直在寻找它,但这是我能想到的唯一可行的方法。

      【讨论】:

      • 您能解释一下“_creds 的更新值”是什么意思吗?我不想每次都调用 api 来获取凭据,因为它们不会改变。只想拨打电话获得一次信用,然后每次使用这些信用。
      • 我的意思是它会在 API 调用完成后更新它,但是 API 调用只进行一次,因为它检查 _creds 是否未定义,并且只有在它仍然未定义时才进行 API 调用跨度>
      • 哦,对不起,我忘记在 else 语句中设置 _creds,所以它实际上每次都会调用 API,这不是我试图做的,如果让你感到困惑,我很抱歉
      【解决方案3】:

      您如何将其作为中间件并在您的应用启动后进行调用,并将数据存储在您的response.locals 中,您可以在其中访问任何您需要的东西。

      【讨论】:

        猜你喜欢
        • 2015-08-23
        • 2011-02-19
        • 1970-01-01
        • 2016-04-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-17
        相关资源
        最近更新 更多