bjoerge / debounce-promise

Create a debounced version of a promise returning function
MIT License
241 stars 27 forks source link

Ability to "cancel" the resolution of former promises. #15

Closed slorber closed 6 years ago

slorber commented 6 years ago

Hi,

For this case:

[1, 2, 3, 4].forEach(num => {
  return saveCycles('call no #' + num).then(value => {
    console.log(value)
  })
})

I'd like to be able to output only one log:

// Will only call expensiveOperation once with argument `4` and print:
//=> call no #4

Basically, the first 3 calls I'd like to be able to do:

const promiseResolver => (promise, isLast) => new Promise((resolve, reject) => {
    promise.then(
      value => isLast() && resolve(value),
      error => isLast() && reject(error),
    );
});

Does it make any sense to you to support such an usecase? I'd be happy to submit a PR for this.

edit: according to what I understand, as of now you return 4 times the same promise so this means it's not possible to do what I want unless returning 4 distinct promises.

bjoerge commented 6 years ago

Hi @slorber Have you seen promise-latest? Even though it does't support cancellation of previous promises (would be happy to accept a PR for that!), it should always resolve with the latest returned promise from the wrapped function.

slorber commented 6 years ago

thanks, will take a look

slorber commented 6 years ago

just wanted to let you know I published a lib that use yours as a dependency and built some additional features on top of it.

https://twitter.com/sebastienlorber/status/1040249449250017285