1

I am trying to keep db queries to a minimum. The goal is to make one query and use data in other functions. So far, I have this code:

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);
})();

The problem is every await getData() invocation drives another db query. How can I avoid that?

Phil
  • 157,677
  • 23
  • 242
  • 245
Tennis Smith
  • 451
  • 6
  • 14

1 Answers1

2

You basically want a lazily initiated, persistent promise result.

Something like this should suffice...

let dataGlobal;

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

The first time getData is called, it will assign the promise returned by GetCoverage() to dataGlobal and return it.

Any subsequent calls will return the already assigned promise.


Here's a quick demo using a fake 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:"));

See also Nullish coalescing assignment (??=)

Phil
  • 157,677
  • 23
  • 242
  • 245