JS Promises: if a handler in a `then` block returns a value vs returning a resolved promise, does the `then` block handle it the same way?

﹥>﹥吖頭↗ 提交于 2021-02-11 14:01:05

问题


Say I have a function that returns a resolved promise like this:

let a = () => {return new Promise(res => res(1))}

and then I then-ify it like this:

a()
.then(val => {return new Promise(res => res(1))})

Here the then contains a handler that returns a promise resolved with 1, so the then block returns a promise resolved with 1 as well. Is that right?

Then say instead we have this:

a()
.then(val => {return 1})

The handler returns 1 instead of returning a promise resolved with 1.

What I Want To Know: Does the then block return a promise resolved with 1 in both of these scenarios, even though one handler returned a resolved promise and the other just returned a value? In other words, does a then block deal with handlers that return promises resolved with a value the same way they deal with handlers that return the value itself?


回答1:


All values returned from a then block are implicitly wrapped in a Promise.resolve, so returning Promise.resolve(1) is unnecessary.



来源:https://stackoverflow.com/questions/61511457/js-promises-if-a-handler-in-a-then-block-returns-a-value-vs-returning-a-resol

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