Mason
Mason

Reputation: 888

What is the difference between Promise.resolve(thenable) and new Promise(thenable.then)?

The question is the title. I'm trying to get a deeper understanding of promises and I think I've figured out how Promise.resolve(thenable) works, or at least mostly how it works, looking at the examples on MDN. I'm wondering if there's a difference between the two. I whipped up this example to show them behaving the same, in way that I would think would show differences in behaviour if there was going to be any. But obviously this test alone isn't good enough to conclude there's nothing different about them, so I've come here.

let thenable = {
    then(resolve) {
        setTimeout(()=>{
            resolve((()=>{
                console.log('test');
                return thenable;
            })());
        }, 1000);
    },
};

let p1 = Promise.resolve(thenable);
let p2 = new Promise(thenable.then);

Upvotes: 6

Views: 1331

Answers (2)

Bergi
Bergi

Reputation: 664327

In your example, the two work mostly the same. You're right, passing resolve and reject to the then method invocation of a thenable is what basically happens when you are resolving a promise with the thenable object.

However, there are a few differences:

  • the then method of a thenable is called as a method on (with the this context as) the thenable object, unlike your new Promise(thenable.then) does - a .bind(thenable) would fix that.
  • Promise.resolve (obviously) has to check first whether the passed object is a thenable at all, it also handles obscure cases where accessing (not calling) .then throws
  • a subtle discrepance in timing: Promise.resolve schedules even the then call asynchronously:

    Promise.resolve({
      get then() {
        console.log("property access");
        return function(res, rej) {
          console.log("method call");
          res("fulfillment");
        };
      }
    }).then(console.log);
    console.log("sync execution end");
    

Upvotes: 5

t.niese
t.niese

Reputation: 40842

There shouldn't be any difference between these two constructs (Promise.resolve(thenable) and new Promise(thenable.then))

  • Both support resolve, reject as parameters.
  • If an error is thrown within the then(resolve) { ... } it will be implicitly catched and the promise will be rejected.
  • Resolving then(resolve) { ... } with thenable would result in infinite recursion.

Upvotes: 2

Related Questions