首页 > 解决方案 > 什么时候 Response.text() 承诺会拒绝?

问题描述

我在MDN/Response/text docs上看到了.text()仅使用 with的示例then

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

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

由于皮棉规则,我需要把

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

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

标签: javascriptpromisefetch-api

解决方案


如果响应已经是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

推荐阅读