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

Accept function? #22

Open
fisker opened this issue Nov 12, 2021 · 3 comments
Open

Accept function? #22

fisker opened this issue Nov 12, 2021 · 3 comments

Comments

@fisker
Copy link
Contributor

fisker commented Nov 12, 2021

const delayed1 = pMinDelay(fn, 1000)
const delayed2 = pMinDelay(fn, 1000, {delayRejection: false})

delayed1() takes at least 1s to settle.
delayed2() takes at least 1s to resolve.

I have similar function in my recent project accepts both Promise and function, I called it slowDown.

@sindresorhus
Copy link
Owner

It's unclear to me what problem accepting a function would solve and how it would handle the function?

@fisker
Copy link
Contributor Author

fisker commented Nov 26, 2021

what problem accepting a function would solve

Before:

const foo = async () => {}

const bar = await pMinDelay(foo())

After

const foo = pMinDelay(async () => {}) 

const bar = await foo()

how it would handle the function?

My implemention

async function slowDownPromise(promise, time) {
  const [result] = await Promise.all([promise, delay(time)])
  return result
}

function slowDownFunction(fn, time) {
  return function (...args) {
    return slowDownPromise(fn.apply(this, args), time)
  }
}

function slowDown(promiseOrFunction, time) {
  return (
    typeof promiseOrFunction === 'function' ? slowDownFunction : slowDownPromise
  )(promiseOrFunction, time)
}

@sindresorhus
Copy link
Owner

Ah. That's a good idea. 👍

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

No branches or pull requests

2 participants