而你却可以随时修好它
return
调整和调整
.then
从逻辑上讲,最好是
avoid the explicit Promise construction antipattern
throw
在它内部停止处理程序并使控制流转到
catch
.
你应该
消费者
fetchJson
接住
在这里,因为当获取失败时,您将返回错误类型的内容—当您
接住
承诺,这在这里是不可取的。
如果你想
JSON.parse
.json()
方法,而不是
.text()
方法,它将自动完成。
export function fetchJson<T>(url: string): Promise<T> {
return fetch(url)
.then((response) => {
if (!response.ok) {
throw new Error(response.statusText);
} else {
return response.json();
}
});
}
// Then in the consumer:
fetchJson<someType>('someURL')
.then((result) => {
// result is of type someType
})
.catch((err) => {
// handle errors here
});