Javascript Promises:多个 .then(..) 子句与一个 .then(..) 子句?

问题描述 投票:0回答:1

上下文是这样的:我有一个“玩具”node.js 服务器,它返回以下 json: {“消息”:“你好”} 如果您向“http://localhost:3060/”发出 GET 请求,则会返回此信息 所以,非常简单。

这是我的“基线”代码,具有多个 .then(..) 子句

  3 function footgun() {
  4     fetch('http://localhost:3060/')
  5             .then(res => res.json())
  6             .then(json => json.message)
  7             .then(msg => console.log(msg));

输出为: 你好

非常好。非常好。这就是我想要的。

我一直在阅读有关如何实施承诺的内容。
所以我知道每个 .then() 返回一个 Promise 对象。但这不是浪费吗?
将所有内容打包到一个 .then() 子句中肯定会更有效吗? 像这样:

  3 function footgun() {
  4     fetch('http://localhost:3060/')
  5             .then(res => {
  6                 const json = res.json();
  7                 const msg = json.message;
  8                 console.log(msg);
  9             });

输出为: 未定义

这就是问题所在。为什么结果是“未定义”? 为什么这在单个 .then(..) 子句中不起作用?

感谢任何自愿提供解释或建议的人。 :-) 基因酮

javascript node.js promise
1个回答
0
投票

只有当您有另一个需要其结果的异步操作时,才应该使用额外的

.then()

所以,在此:

  3 function footgun() {
  4     fetch('http://localhost:3060/')
  5             .then(res => res.json())
  6             .then(json => json.message)
  7             .then(msg => console.log(msg));

您需要一个

.then()
来表示
fetch()
,并且您需要一个来表示
res.json()
,因为两者都是异步的并且都返回一个承诺。

您不需要这个:

.then(json => json.message)

因为它只是浪费了一些你不需要做的周期。在您展示的顺序中,这将是最有效的:

  3 function footgun() {
  4     fetch('http://localhost:3060/')
  5             .then(res => res.json())
  6             .then(data => console.log(data.msg));

仅对返回 Promise 的每个异步操作使用

.then()


当然,如果使用await就更简单了:

  3 async function footgun() {
  4     let res = await fetch('http://localhost:3060/');
  5     let data = await res.json();
  6     console.log(data.msg);

同样,只有当您有返回 Promise 的异步操作时,才使用

await

© www.soinside.com 2019 - 2024. All rights reserved.