【问题标题】:what's the difference between using then in argument and not在参数中使用 then 和 not 有什么区别
【发布时间】:2022-01-07 07:35:11
【问题描述】:

这两个promise有什么区别,一个用在参数other outisde中,哪个是首选

fetch(API_URL + "films")
  .then(response => response.json())
  .then(films => {
    output.innerText = getFilmTitles(films);
  })
  .catch(error => output.innerText = ":(")

fetch(API_URL + "films")
  .then(response => 
    response.json()
      .then(films => {
        output.innerText = getFilmTitles(films);
      }))
  .catch(error => output.innerText = ":(")

【问题讨论】:

  • 第二个语法无效。
  • @AKX 为什么语法无效? response.json() 返回一个承诺,它可以是 then()'d 就可以了吗?
  • @AKX 我的意思是,只有右括号。所以..有点不必要的评论
  • 你刚刚错过了一个结束)。假设这是一个错字,我在答案中添加了它。
  • 请使用正确的括号更正您的语法,以便我们确定您的意思。您的第二个选项没有匹配的括号。

标签: javascript async-await es6-promise


【解决方案1】:

这可能是基于意见的。我认为第一个是首选,因为您不会得到嵌套的 Promise,并且应该更易于阅读。

为了更明显:

fetch(API_URL + 'films')
  .then(response => response.json())
  .then(films => {
    output.innerText = getFilmTitles(films);
  })
  .catch(error => output.innerText = ':(');

fetch(API_URL + 'films')
  .then(response => response.json()
    .then(films => {
      output.innerText = getFilmTitles(films);
    })
    .catch(error => output.innerText = ':(')
  );

第二种方式的缩进数量会增加,而第一种方式的缩进数量是固定的。

【讨论】:

  • 我们可以通过切换到await 而不是使用then 来减少对嵌套函数的所有需求。
  • 是的。除了OP提到的之外,这将是第三种选择。假设 OP 可以使用async/await
  • 感谢您的回答
猜你喜欢
  • 2017-02-25
  • 1970-01-01
  • 2010-09-14
  • 2017-04-29
  • 2011-05-09
  • 1970-01-01
  • 1970-01-01
  • 2020-05-25
相关资源
最近更新 更多