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

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-25 09:28:35

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/42539369/promise-resolve-inside-then-method-does-not-pass-its-resolved-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!