then / is-promise

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

Checking obj.catch #6

Closed jamiebuilds closed 9 years ago

jamiebuilds commented 9 years ago

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 commented 9 years ago

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).