【问题标题】:When Response.text() promise will reject?什么时候 Response.text() 承诺会拒绝?
【发布时间】:2021-10-14 22:52:54
【问题描述】:

我在MDN/Response/text 上看到文档显示了仅将.text()then 一起使用的示例

response.text().then(function (text) {
  // do something with the text response
});

它返回一个用字符串解析的承诺。

由于 lint 规则,我需要放置

// eslint-disable-next-line @typescript-eslint/no-floating-promises
res.text().then(async (t) => {

当我需要从Response.text() 捕获被拒绝的承诺时,是否有用例?也许有一些例子?

【问题讨论】:

  • “给定对象和类型的消费主体算法运行以下步骤: 1. 如果对象不可用,则返回一个以 TypeError 拒绝的承诺,...。” , "如果一个对象包含 Body 接口 mixin,如果它的 body 是非 null 并且它的 body 的流是 disturbedlocked,则说它是不可用的。"
  • 当流关闭或中止时它确实会失败,尽管我不确定何时/是否会发生这种情况。当出现 UTF-8 编码错误时它不会失败,它只是用 U+FFFD 替换它。我也想知道如果有Content-Length不匹配是否会失败

标签: javascript promise fetch-api


【解决方案1】:

如果响应已经是consumed/read,它可能会失败/拒绝,也就是说,如果上面已经调用了 .text/.json 等。

查看 polyfill 实现 (https://github.com/github/fetch/blob/d1d09fb8039b4b8c7f2f5d6c844ea72d8a3cefe6/fetch.js#L301 ) 我没有看到其他可能的情况。


例子:

response.text()
  .then(t1 => {
    console.log({ t1 }); // after calling text() we can see the result here
    return response; // but we decided to return the response to the next handler
  })
  .then(res =>res.text()) // here we try to read text() again
  .then(t2 => console.log({ t2 })) // and expecting text to be logged here
  .catch(er => console.log({ er })); // but the text() promise rejects with 
  // TypeError: Failed to execute 'text' on 'Response': body stream already read

【讨论】:

    猜你喜欢
    • 2013-01-28
    • 1970-01-01
    • 2021-07-30
    • 2020-02-08
    • 2013-10-23
    • 2019-11-25
    • 2021-12-22
    • 2016-08-12
    相关资源
    最近更新 更多