JS承诺:如果`then`块中的处理程序返回一个值而不是返回一个已解析的Promise,那么`then`块是否以相同的方式处理它? [英] 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?
问题描述
说我有一个函数,返回的是这样的已解决的诺言:
Say I have a function that returns a resolved promise like this:
let a = () => {return new Promise(res => res(1))}
然后我像这样然后修改
:
a()
.then(val => {return new Promise(res => res(1))})
此处 then
包含一个处理程序,该处理程序返回以 1
解析的承诺,因此 then
块返回一个以解析的承诺.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})
处理程序返回 1
,而不是返回用 1
解析的承诺.
The handler returns 1
instead of returning a promise resolved with 1
.
我想知道的内容:在这两种情况下,即使一个处理程序, then
块是否也会返回用 1
解析的承诺返回了一个已解决的承诺,另一个刚刚返回了一个值?换句话说, then
块是否以与处理返回值本身的处理程序相同的方式处理返回用值解析的promise的处理程序?
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?
推荐答案
从 then
块返回的所有值都隐式包装在 Promise.resolve
中,因此返回 Promise.resolve(1)
是不必要的.
All values returned from a then
block are implicitly wrapped in a Promise.resolve
, so returning Promise.resolve(1)
is unnecessary.
这篇关于JS承诺:如果`then`块中的处理程序返回一个值而不是返回一个已解析的Promise,那么`then`块是否以相同的方式处理它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!