1// Copyright (C) 2024 The Android Open Source Project 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); 4// you may not use this file except in compliance with the License. 5// You may obtain a copy of the License at 6// 7// http://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS, 11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12// See the License for the specific language governing permissions and 13// limitations under the License. 14 15import {AsyncLazy} from './async_lazy'; 16import {defer} from './deferred'; 17import {errResult, okResult, Result} from './result'; 18 19async function slowFactory(res: number): Promise<Result<number>> { 20 const barrier = defer<void>(); 21 setTimeout(() => barrier.resolve(), 0); 22 await barrier; 23 return isFinite(res) ? okResult(res) : errResult(`${res} is not a number`); 24} 25 26test('AsyncLazy', async () => { 27 const alazy = new AsyncLazy<number>(); 28 expect(alazy.value).toBeUndefined(); 29 30 // Failures during creation should not be cached. 31 expect(await alazy.getOrCreate(() => slowFactory(NaN))).toEqual( 32 errResult('NaN is not a number'), 33 ); 34 expect(await alazy.getOrCreate(() => slowFactory(1 / 0))).toEqual( 35 errResult('Infinity is not a number'), 36 ); 37 38 const promises = [ 39 alazy.getOrCreate(() => slowFactory(42)), 40 alazy.getOrCreate(() => slowFactory(1)), 41 alazy.getOrCreate(() => slowFactory(2)), 42 ]; 43 44 // Only the first promise will determine the result, which will be 45 // subsequently cached. 46 expect(await Promise.all(promises)).toEqual([ 47 okResult(42), 48 okResult(42), 49 okResult(42), 50 ]); 51 expect(alazy.value).toEqual(42); 52 53 alazy.reset(); 54 expect(await alazy.getOrCreate(() => slowFactory(99))).toEqual(okResult(99)); 55}); 56