then / is-promise

Test whether an object looks like a promises-a+ promise
MIT License
282 stars 32 forks source link

Why would I use this? #38

Closed KooiRUG closed 4 years ago

KooiRUG commented 4 years ago

I don't think this is a very useful snippet, sorry.

console.log(isPromise({then: () => {}}));

nicolo-ribaudo commented 4 years ago

That code works like an alternative implementation of a promise. For example await will call that .then function.

Miladiir commented 4 years ago

I would suggest informing yourself on how promises work. They are not as suffisticated as you might think. What you implemented is actually a promise-like function as nicolo said. It works as an alternative implementation to the browser/node implementation of a promise. As you might already know, there are many of these implementations e.g. Bluebird. This function "catches" them all.

There is something to be said, however, on why this would need a package of it's own...

jimmywarting commented 4 years ago

There is also the possibility to write code in a style that can handle both scenarios (by always treating it as a promise) - so you don't have to check it

async function log (something_unknown) {
  console.log(await something_unknown)
}

// or 
function log (something_unknown) {
  return Promise.resolve(something_unknown).then(console.log)
}

promise = log(Promise.resolve(5)) // prints 5
promise = log(4) // prints 4

So yea, maybe you don't need this package

ForbesLindesay commented 4 years ago

Please seriously consider what you're doing before you post in this tone. This question has been asked and answered many times in the issue tracker for is-promise, so search those if you want a full answer, but the short answer is that:

  1. The reason this library treats your example as a Promise is that the Promises spec requires any object or function with a .then method to be treated as a Promise.
  2. The reason the spec requires that is because it allows interoperability between the many Promise implementations that existed before native promises. Without this, promises would be virtually unusable for years while everyone migrated.
  3. This library exists, even though it's only 3 lines because it means you don't have to think about exactly these problems. Lots of people know little enough about Promises that they wouldn't be able to implement this correctly (see all the pull requests & comments offering to "simplify" the logic). That's fine, they shouldn't need to worry about that, they can just import is-promise.

I hope I've answered your question, but more importantly I hope @KooiRUG and @Miladiir will think more about the impact of their comments in future. Comments like these are a massive drain on the time and energy of open source maintainers, the questions you raise are already answered hundreds of times over, and they contribute absolutely nothing to society.