| b69ab31 | | | 1 | /** |
| b69ab31 | | | 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. |
| b69ab31 | | | 3 | * |
| b69ab31 | | | 4 | * This source code is licensed under the MIT license found in the |
| b69ab31 | | | 5 | * LICENSE file in the root directory of this source tree. |
| b69ab31 | | | 6 | */ |
| b69ab31 | | | 7 | |
| b69ab31 | | | 8 | // See https://advancedweb.hu/the-async-lazy-initializer-pattern-in-javascript/ |
| b69ab31 | | | 9 | |
| b69ab31 | | | 10 | /** |
| b69ab31 | | | 11 | * Because Promises are eager in JavaScript, we need to introduce an extra layer |
| b69ab31 | | | 12 | * to lazily invoke an async operation. lazyInit() takes a function that |
| b69ab31 | | | 13 | * represents the async operation, but does not call it until the function |
| b69ab31 | | | 14 | * returned by lazyInit() itself is called. Note that lazyInit() is idempotent: |
| b69ab31 | | | 15 | * once it is called, it will always return the original Promise created by |
| b69ab31 | | | 16 | * calling the async operation. |
| b69ab31 | | | 17 | * |
| b69ab31 | | | 18 | * ``` |
| b69ab31 | | | 19 | * // Note getObj is a *function*, not a *Promise*. |
| b69ab31 | | | 20 | * const getObj = lazyInit(async () => { |
| b69ab31 | | | 21 | * const value = await expensiveOperation(); |
| b69ab31 | | | 22 | * return value + 1; |
| b69ab31 | | | 23 | * }); |
| b69ab31 | | | 24 | * |
| b69ab31 | | | 25 | * ... |
| b69ab31 | | | 26 | * |
| b69ab31 | | | 27 | * // expensiveObjCreation() will not be called until getObj() is called, and if |
| b69ab31 | | | 28 | * // it is called, it will only be called once. |
| b69ab31 | | | 29 | * const objRef1 = await getObj(); |
| b69ab31 | | | 30 | * const objRef2 = await getObj(); |
| b69ab31 | | | 31 | * ``` |
| b69ab31 | | | 32 | */ |
| b69ab31 | | | 33 | export default function lazyInit<T>(init: () => Promise<T>): () => Promise<T> { |
| b69ab31 | | | 34 | let promise: Promise<T> | null = null; |
| b69ab31 | | | 35 | return () => (promise = promise ?? init()); |
| b69ab31 | | | 36 | } |