str*_*605 6 javascript promise fetch-api
我看到MDN/Response/text.text()文档上显示了仅使用的示例then
response.text().then(function (text) {
// do something with the text response
});
Run Code Online (Sandbox Code Playgroud)
它返回一个用字符串解析的承诺。
由于 lint 规则,我需要放置
// eslint-disable-next-line @typescript-eslint/no-floating-promises
res.text().then(async (t) => {
Run Code Online (Sandbox Code Playgroud)
当我需要捕获被拒绝的承诺时,是否有用例Response.text()?也许一些例子?
如果响应已经consumed/读取,那么它可能会失败/拒绝,也就是说,如果上面已经调用了 .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
Run Code Online (Sandbox Code Playgroud)