我看到在MDN/Response/text文档中显示了仅使用.text()
和then
的示例
response.text().then(function (text) {
// do something with the text response
});
它返回一个promise,用String解析。
由于lint规则,我需要把
// eslint-disable-next-line @typescript-eslint/no-floating-promises
res.text().then(async (t) => {
当我需要从Response.text()
捕获被拒绝的承诺时,是否有用例?也许可以举一些例子?
如果响应已经是consumed
/read,那么它可以失败/拒绝,也就是说,如果已经调用了。text/。
查看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