代码之家  ›  专栏  ›  技术社区  ›  Tennis Smith

如何进行一次异步数据库调用并为后续函数保存输出?

  •  1
  • Tennis Smith  · 技术社区  · 3 年前

    我正在尽量减少数据库查询。目标是 在其他功能中查询和使用数据。到目前为止,我有以下代码:

    async function GetCoverage(scroll_path) {
      const apiName = "xxxx";
      const path = "/scrolls/" + scroll_path;
      const myInit = {
        headers: {},
        response: false,
      };
      const response = await API.get(apiName, path, myInit);
      console.log("response:", response);
      return response.Items;
    }
    
    let dataGlobal;
    
    const getData = async () => {
      const response = await GetCoverage("all");
      dataGlobal = response;
      return response;
    };
    
    (async () => {
      await getData();
      console.log("dataGlobal:", dataGlobal);
    })();
    

    问题是每个 await getData() 调用驱动另一个数据库查询。我该如何避免这种情况?

    1 回复  |  直到 3 年前
        1
  •  2
  •   Phil    3 年前

    你基本上想要一个懒散的开始,持久的承诺结果。

    这样的东西应该足够了。。。

    let dataGlobal;
    
    const getData = () => (dataGlobal ??= GetCoverage("all"));
    

    第一次 getData 被调用时,它将分配由返回的承诺 GetCoverage() dataGlobal 并将其退回。

    任何后续调用都将返回已分配的promise。


    这里有一个使用假的快速演示 GetCoverage

    // mock
    const GetCoverage = () => {
      console.log("GetCoverage called");
      return new Promise((r) => {
        setTimeout(r, 1000, Math.random());
      });
    }
    
    let dataGlobal;
    
    const getData = () => (dataGlobal ??= GetCoverage("all"));
    
    // Make parallel calls
    getData().then(console.log.bind(null, "Result #1:"));
    getData().then(console.log.bind(null, "Result #2:"));
    getData().then(console.log.bind(null, "Result #3:"));

    另请参阅 Nullish coalescing assignment (??=)