0

For sync code I do:

 return opts || (opts = getOpts())

To make sure things are easily cached/initialized.

What is the easiest to do this in async/promise pattern?
Currently I have a repeating boilerplate

if (result) {
   return Promise.resolve(result);
} else {
   return getResult().then(_result => {
       result = _result;
       return result;
   }
}

Which is annoying when done multiple times.
Libraries I find are either unmaintained or offer unfriendly syntax.

Any suggestions or ideas?

guy mograbi
  • 27,391
  • 16
  • 83
  • 122
  • 1
    `return opts || await getOpts();` – Kevin B Nov 29 '18 at 19:18
  • Cache the promise, not the data delivered by it. – Roamer-1888 Nov 29 '18 at 20:12
  • 1
    I think it should be noted that the idea of lazy initialization (if that's what this is about) is inherently synchronous. It says, initialize data *exactly when it's needed*. All we can do with async is *begin initialization* exactly when the data is needed, i.e. initialize the data *after* it's needed. – danh Nov 29 '18 at 20:31
  • @Roamer-1888 that introduces a problem as the promise will resolve just once. There's an assumption that every consumer has to return original result which I want to avoid. – guy mograbi Nov 29 '18 at 22:22
  • I don't understand your point about consumers having to return original result. As with every promise, the cached promise will settle (resolve or reject) only once (or remaining pending). That shouldn't be a problem bacause the cached promise can have multiple consumers - as many as you want - with no constraints on what the consumers do with the delivered data. – Roamer-1888 Nov 30 '18 at 01:00
  • @Roamer-1888 maybe I am mistaken. can you provide a working example? – guy mograbi Dec 03 '18 at 21:36
  • 1
    Ther are many examples here in StackOverflow. [This one is as good as any](https://stackoverflow.com/a/18745499/3478010). – Roamer-1888 Dec 05 '18 at 00:18

1 Answers1

1

You can achieve a more friendly syntax with the await keyword like this

if (!result) result = await getResult();
return result;