为什么`res.json()`和`next()`不返回一个`Promise>`?

huangapple go评论78阅读模式
英文:

Why doesnt res.json() and next() return a Promise<Promise<Thing>>

问题

我正在学习JavaScript中的异步函数,对于为什么感到困惑。

嗨,我对JavaScript还很陌生,对Promises和then如何工作有疑问。就我理解,then返回一个Promise,所以

fetch(someApi)
  .then((res) => res.json())
  .then((data) => data)

我的问题是,既然res.json()和then()都返回一个Promise,为什么第二行的结果不是Promise<Promise>?

英文:

Im currently learning asynchronous function in javascript and im confused as to why

Hello im quite new to javascript and i have a question on how Promises and then work
to my understanding the then returns a promise so

fetch(someApi)         
  .then((res)=&gt;res.json())         
  .then((data)=&gt;data)

my question is that since res.json() and then() both return a promise, why wouldnt the result of the 2nd line be a Promise<Promise<Thing>>,

答案1

得分: 1

来自Promise的then文档

如果处理程序函数:

...

返回另一个待定承诺:then返回的承诺的实现/拒绝将在处理程序返回的承诺的实现/拒绝之后。此外,then返回的承诺的解析值将与处理程序返回的承诺的解析值相同。


即传递给第二个 then的回调函数将接收来自传递给第一个 then的回调函数返回的已解析值。

英文:

From the documentation for then:

> If the handler function:

...

> returns another pending promise: the fulfillment/rejection of the promise returned by then will be subsequent to the resolution/rejection of the promise returned by the handler. Also, the resolved value of the promise returned by then will be the same as the resolved value of the promise returned by the handler.


i.e. The callback function passed to the second then will receive the resolved value of the promise returned from the callback function passed to the first then.

huangapple
  • 本文由 发表于 2023年3月3日 22:49:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/75628549.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定