2

I'm new to Promises and I'm trying to understand the Promise constructor. According to promisejs.org, something which is maybe a promise can be resolved using Promise.resolve, e.g.

var maybePromise = Math.random() > 0.5 ? 10 : Promise.resolve(10);
var definitelyPromise = Promise.resolve(maybePromise);

Promise.resolve is equivalent to (case1):

var definitelyPromise = new Promise(function (fulfill, reject) {
  if (isPromise(maybePromise)) {
    maybePromise.then(fulfill, reject);
  } else {
    fulfill(maybePromise);
  }
});

I wonder if this is also equivalent to (case2):

var definitelyPromise3 = new Promise(function(fulfill, reject) {
  if (maybePromise instanceof Promise) {
    fulfill(maybePromise);
  } else {
    fulfill(maybePromise);
  }
});

(Of course the if...else... can be removed, because I call fulfill(maybePromise) in both cases).

Here's a jsfiddle

krombi
  • 504
  • 1
  • 4
  • 15
  • It depends on what `isPromise` function does. `maybePromise instanceof Promise` only checks whether `maybePromise` is instance of `Promise` constructor, while `isPromise` could check whether `maybePromise` is any then-able. – Michał Miszczyszyn Apr 13 '16 at 09:05
  • Michał, the sample in promisejs.org uses a `isPromise`, but I don't know where this function is implemented or how to implement on my own. Could you please give me a sample demonstrating different behaviour of case1 and case2 if an arbitrary then-able is used? – krombi Apr 13 '16 at 09:43

1 Answers1

3

In fact, the first argument of the promise constructor callback is called resolve, not fulfill.

When you pass a promise or thenable into resolve, its state will get adopted, all other values fulfill the promise directly. This means that exactly the logic you were describing is implemented right within resolve - and, as you said, you don't need the condition in the resolver callback.

And in fact, the standard specifies Promise.resolve to be implemented quite like

function resolve(x) {
    return new Promise(function(resolve, reject) {
        resolve(x);
    });
}
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • This means case1 and case2 are both correct implementations and behave exactly the same way? Btw: I used `fulfill` instead of `resolve` because the sample is copied from promisejs.org – krombi Apr 13 '16 at 12:26
  • @krombi: It depends on what `isPromise` does whether case 1 is behaving in *exactly* the same way, but in general the idea is correct. – Bergi Apr 13 '16 at 12:31
  • Damn, in my question I used `isPromise` from jspromise.org for case1, but in my jsfiddle I use `if (maybePromise instanceof Promise)` in both cases... – krombi Apr 13 '16 at 13:40