【问题标题】:How to use fetch when I am not interested in the returned value?当我对返回值不感兴趣时​​如何使用 fetch?
【发布时间】:2021-03-11 05:00:10
【问题描述】:

我通常这样使用fetch

fetch(`http://some.api.com`)
  .then(r => r.json())
  .then(r => someFunctionThatUsesR(r))

我最近遇到一个需要调用 API 的案例

  • 对结果不感兴趣
  • 我需要在完成时调用另一个函数
fetch(`http://some.api.com`)
  .then(r => r.text())
  .then(r => someFunction())

这可行,但我的 IDE 警告我 r 未被使用。

这让我想到了一个问题:有没有更好/更多的 JSonic JavaScriptic 方式来处理这个问题?(= 这样就不需要在then()s)

【问题讨论】:

  • 不会使用someFunction(r) 摆脱那个警告吗? “JSonic”是什么意思?
  • 只使用.then(() => someFunction())(与.then(someFunction)相同,假设someFunction不引用this
  • @evolutionxbox 我认为他的意思是 JavaScriptic,一种 Pythonic。
  • .json()isn't unnecessary。它将响应流转换为 json 格式的正文
  • @evolutionxbox,正如 Barman 所说——我复制了“Pythonic”,我会将其更改为正确的表达方式

标签: javascript fetch-api


【解决方案1】:

如果您不使用结果,则不需要r 参数。你也不需要打电话给r.text()

fetch(`http://some.api.com`)
    .then(() => someFunction());

【讨论】:

【解决方案2】:

你可以写

fetch(`http://some.api.com`)
  .then(r => r.text())
  .then(someFunction)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-23
    • 1970-01-01
    • 2020-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多