我有以下代码:
fetch(
url,
{ ...data }
).then((response) => {
if (!response.ok) throw new Error(response.statusText);
return response.json();
}).then((response) => {
resolve(response);
}).catch((error) => {
console.log('error', error);
reject(error);
});
当我执行请求并获得404
时,console.log('error')
行会运行,但我仍然在控制台中出现错误:
GET https://swapi.co/api/people/0/ 404 ()
Uncaught (in promise) Error
at http.js:10
我无法弄清楚为什么会发生这种情况,如果catch()
块正在运行,为什么会说uncaught (in promise)
?
你打电话给reject
,所以这指出的承诺将被拒绝,如果你没有抓到那个未被捕获的。解决这个问题:
What is the explicit promise construction antipattern and how do I avoid it?