Created
August 26, 2021 03:36
-
-
Save segg21/61092632671a32b668b750f93c9ae5cb to your computer and use it in GitHub Desktop.
Javascript Lock Method/Function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Some thoughts about Javascript, there's no threads but what if this happens? | |
I may also be a bad way to use while, as I thought maybe the lock object should hold | |
any functions that must be called.. I may just update this in the future, but this is potentially | |
a way you could lock executions for something? Have fun! | |
Author. S.R (Segfault) | |
Date: Aug 25, 2021 | |
*/ | |
const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); | |
function lock(l) { | |
// lock will return a function, so you can pass a callback function that'll be called within the lock | |
return function(func) { | |
// after calling the return function with your callback, a promise is then return | |
return new Promise(async (r) => { | |
// if the object (l) is locked, wait until it's unlocked | |
while (l.isLocked) | |
await sleep(500); | |
// before we execute a function, we must lock | |
l.isLocked = true | |
return (await async function() { | |
// call your callback function, catch if error resolving null | |
try { r(await func()) } catch { r(null) } | |
// whatever happens, this will always be unlocked, and the while loop will allow something else to pass through | |
// and the process continues. | |
l.isLocked = false; | |
})(); | |
}) | |
} | |
} | |
// lock object, needed to lock anything for that instances (don't use for multiple locks) | |
const _lock = new Object(); // {} | |
for(let i = 0; i < 100; i++){ | |
// pass lock, and an object. it'll return a function for you to pass a callback function that'll | |
// execute within the lock. it can be async, as in the text below. | |
lock(_lock)(async () => { | |
// your function to run in the lock, after this lock closes any other | |
// calls to lock will execute since they're being awaited (sleeping) | |
await sleep(Math.random() * 5E3); | |
console.log('I finished!'); | |
}); | |
} | |
console.log('for loop done, waiting for 100 finished calls :P'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment