@@ -3,25 +3,29 @@ const { lock } = require('proper-lockfile')
33const staleSeconds = 30
44
55// Obtains a lock on the path, and maintains it until the callback finishes
6- async function withLock ( path , options = { } , callback = options ) {
7- // Obtain the lock
8- const releaseLock = await lock ( path , {
9- retries : 10 ,
10- update : 1000 ,
11- stale : staleSeconds * 1000 ,
12- realpath : ! ! options . mustExist ,
13- onCompromised : ( ) => {
14- throw new Error ( `The file at ${ path } was not updated within ${ staleSeconds } s.` )
6+ function withLock ( path , options = { } , callback = options ) {
7+ return new Promise ( async ( resolve , reject ) => {
8+ let releaseLock , result
9+ try {
10+ // Obtain the lock
11+ releaseLock = await lock ( path , {
12+ retries : 10 ,
13+ update : 1000 ,
14+ stale : staleSeconds * 1000 ,
15+ realpath : ! ! options . mustExist ,
16+ onCompromised : ( ) =>
17+ reject ( new Error ( `The file at ${ path } was not updated within ${ staleSeconds } s.` ) )
18+ } )
19+ // Hold on to the lock until the callback's returned promise resolves
20+ result = await callback ( )
21+ } catch ( error ) {
22+ reject ( error )
23+ // Ensure the lock is always released
24+ } finally {
25+ await releaseLock ( )
1526 }
27+ resolve ( result )
1628 } )
17-
18- // Try executing the callback, waiting for its returned promise to resolve
19- try {
20- return await callback ( )
21- } finally {
22- // Ensure the lock is always released
23- releaseLock ( )
24- }
2529}
2630
2731module . exports = withLock
0 commit comments