Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

call of unlock() is too convoluted #9

Open
ceresith opened this issue May 2, 2016 · 3 comments
Open

call of unlock() is too convoluted #9

ceresith opened this issue May 2, 2016 · 3 comments

Comments

@ceresith
Copy link

ceresith commented May 2, 2016

lock('key', function(unlock) { unlock()(); })

Currently, this is too convoluted. It should be:

lock('key', function(unlock) { unlock(); })

@dominictarr
Copy link
Owner

your example code is misleading because you are not doing anything that is async.

when you use it as a callback, as given in the examples, it is not as bad.

lock(key, function(unlock) {
  fs.readFile(key, unlock())
})

@alflennik
Copy link

In the age of async / await this feels a little odd. I had to do this:

await new Promise((resolve, reject) => {
  lock('key', async unlock => {
    await asyncFunction()
    unlock()();
    resolve();
  });
});

It would be awesome if the callback could await a promise before releasing. Then I could do this:

  await lock('key', async () => {
    await asyncFunction()
  });

@poislagarde
Copy link

@alflennik we promisify it like this:

function promisifiedLock () {
  const lock = Lock()
  return (key) =>
    new Promise((resolve) => {
      lock(key, (release) => {
        resolve(promisifyRelease(release))
      })
    })
}

function promisifyRelease (release) {
  return () =>
    new Promise((resolve, reject) => {
      release((err) => {
        if (err) {
          reject(err)
        } else {
          resolve()
        }
      })()
    })
}

then use it like this:

const lock = promisifiedLock()

const release = await lock('key')
try {
  await asyncFunction()
} finally {
  await release()
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants