javascript - 什么时候 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()
?也许有一些例子?
解决方案
如果响应已经是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
推荐阅读
- python - 有没有办法为 SWIG 的默认标准字符串参数生成函数注释?
- video - 如何将“scale2ref”集成到这个 ffmpeg 代码中?
- android - 如何使用 OneSignal 从 android 应用程序发送字符串?
- reactjs - 为什么我获取的数据没有出现在我的 React hooks 组件中?
- javascript - 入口点和基于路由的拆分有什么区别
- git - 在 vagrant 中更新 git 凭据
- javascript - 页面加载时运行的 JavaScript
- css - 动画右侧的关闭侧面板
- python - Cartopy 和 PIL 的问题
- reactjs - TypeError:无法读取 null React JS 的属性“包含”