【发布时间】:2021-10-17 07:46:40
【问题描述】:
我有三个函数functionA、functionB和functionC。
为什么functionC 中的.then(id)... 块会运行,即使functionB 抛出错误并以catch 语句结束。
我确定我错过了关于承诺的重要内容。
const functionA = () => {
return fetch("http://localhost:3001/types")
.then((response) => response.json())
.then((data) => data)
.catch((error) => error);
};
const functionB = (type) => {
return functionA()
.then((response) => response.filter((item) => item.name === type))
.then((result) => {
if (result.length !== 1) { // assume for this example this is truthy
const error = new Error("no type found or found more than one");
throw error;
} else {
return result[0].id;
}
})
.catch((error) => error); // this runs as expected since we're throwing an error above
};
const functionC = (x, y) => {
return functionB(y)
.then((id) => { //why does this block run?
//..do something
})
.catch((error) => console.log("functionB threw an error"));
};
【问题讨论】:
-
正是因为您已经捕获错误,这使得链能够成功继续。
-
旁注:
.then((data) => data)从来没有任何理由。它只是引入了一个额外的异步分辨率,而没有改变任何东西。
标签: javascript promise