import { assert } from "chai" ; import { AsyncMutex } from "../AsyncMutex" ; import { BeDuration } from "../Time" ; describe ( "AsyncMutex" , ( ) => { before ( async ( ) => { } ) ; const mutex = new AsyncMutex ( ) ; let currValue = 0 ; const addOneWithoutMutex = async ( ) : Promise < void > => { await BeDuration . wait ( 1000 ) ; currValue += 1 ; } ; const multiplyTwoWithMutex = async ( ) : Promise < void > => { const unlock = await mutex . lock ( ) ; currValue *= 2 ; unlock ( ) ; } ; it ( "should be honored" , async ( ) => { const promises = new Array < Promise < void > > ( ) ; let ii = 0 ; currValue = 0 ; while ( ii ++ < 10 ) { promises . push ( multiplyTwoWithMutex ( ) ) ; promises . push ( addOneWithoutMutex ( ) ) ; } await Promise . all ( promises ) ; assert . equal ( currValue , 10 ) ; const unlock = await mutex . lock ( ) ; ii = 0 ; currValue = 0 ; while ( ii ++ < 10 ) { promises . push ( multiplyTwoWithMutex ( ) ) ; promises . push ( addOneWithoutMutex ( ) ) ; } promises . push ( BeDuration . wait ( 2000 ) . then ( ( ) => unlock ( ) ) ) ; await Promise . all ( promises ) ; assert . equal ( currValue , 10240 ) ; } ) ; } ) ;