Search code examples
es6-promise

Promise.resolve inside then() method does not pass its resolved value


I found an interest thing about Promise. When I run the following codes, it gave me the output of 'aa' as oppose to 'bb', which confused me a lot. Does anyone understand why and give a explanation, please? Thanks!

Promise.resolve('aa')
.then(Promise.resolve('bb'))
.then(console.log);


Solution

  • Well, you're misusing a .then() handler so it is no surprise that you don't get the desired answer.

    A .then() handler should be passed a function reference. You are passing it a promise which it dutifully ignores because it's not a callable function.

    When you do this:

    .then(Promise.resolve('bb'))
    

    That executes Promise.resolve('bb') immediately and passes the return result (which is a promise) to .then(). So, you're passing a promise to .then() when you should be passing a function reference. If you change your code to this, then you will get what you expect:

    Promise.resolve('aa')
        .then(function() {return Promise.resolve('bb');})
        .then(console.log);

    Remember, the point of passing something to .then() is that it can be executed LATER when the parent promise resolves/rejects. So, for that to be possible, you have to pass a function reference that can be called by the promise infrastructure at some later time.

    Using ES6 syntax, you could shorten to this:

    Promise.resolve('aa')
      .then(_ => Promise.resolve('bb))
      .then(console.log);