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

Checking obj.catch #6

Closed
jamiebuilds opened this issue Sep 17, 2015 · 1 comment
Closed

Checking obj.catch #6

jamiebuilds opened this issue Sep 17, 2015 · 1 comment

Comments

@jamiebuilds
Copy link

Just got caught up using is-promise with a jQuery.Deferred as then is defined but catch is not. Since this is is-promise and not is-thenable I figured it might be a good idea to check catch as well.

return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function' && typeof obj.catch === 'function';
@ForbesLindesay
Copy link
Member

This isn't really designed to check whether something is an instance of Promise, for that I would suggest using obj instanceof Promise. Instead, it's designed to detect whether something should be treated as a promise. Think of it as answering the question, if I returned this from a .then handler, would it be treated as a Promise.

It lets you create fast paths for synchronous optimisation. For example, consider the following:

function processSequence(seq) {
  var i = 0;
  function next(result) {
    if (i >= seq.length) return result;
    return Promise.resolve(seq[i++](result)).then(next, reject);
  }
  return next();
}
processSequence([
  () => readFileAsync('foo.json'),
  str => JSON.parse(str),
  data => fetch(data.url)
]);

We could use is-promise to improve the performance of that code by only recursing when we actually needed to:

function processSequence(seq) {
  var i = 0;
  function next(result) {
    if (i >= seq.length) return result;
    while (i < seq.length && !isPromise(result)) {
      result = seq[i++](result);
    }
    return Promise.resolve(result).then(next, reject);
  }
  return next();
}
processSequence([
  () => readFileAsync('foo.json'),
  str => JSON.parse(str),
  data => fetch(data.url)
]);

This new example won't waste time converting the result of JSON.parse into a promise, just to immediately wait for that promise. Other than that they're identical.

By checking .catch we would miss lots of things that can be assimilated as promises. As for the name, think of this module as "is Promises/A+", since it predates the ES6 spec and was originally written to match what Promises/A+ would be able to assimilate (which happens to match what ES6 can assimilate).

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

2 participants