我想澄清如何将 Promise 传递给 .catch
以及 .catch
用它做什么。
以此为例:
function fetchDog(){
fetch("https://dog.ceo/api/breeds/image/fail")
.then(response => response.json())
.then(data => console.log(data))
.catch(function(err) {
console.log('Fetch problem');
});
};
fetchDog();
查看 MDN 中的此声明:
If the Promise that then is called on adopts a state (fulfillment or rejection) for which then has no handler, a new Promise is created with no additional handlers, simply adopting the final state of the original Promise on which then was called.
我将其翻译为,在我的示例中,.then
返回一个新的 Promise,它是调用 .then
的 Promise 的副本。
当它到达 .catch
时,我知道 .catch
会在控制台上打印一些内容。 spec还说它的行为与调用 Promise.prototype.then(undefined, onRejected) 相同。
因此,根据 .then
规范的摘录:
If a handler function: doesn't return anything, the promise returned by then gets resolved with an undefined value.
我希望 .catch
返回一个新的 promise ,该 promise “通过”未定义的值来解决。 (对于用未定义的值“解析”的 Promise 对象来说,这到底意味着什么)?
这是真的吗?
最佳答案
.then()
在 Promise 解决时调用其回调。 .catch()
仅在 Promise 被拒绝时调用其回调。
如果fetch()
成功,它就会解决它的promise,因此只调用.then()
回调。
如果 fetch()
收到错误,它会拒绝其 promise ,并且 .catch()
回调将被调用。此外,如果 response.json()
收到错误(例如,响应不是有效的 JSON),它将拒绝该 Promise,并且 .catch()
将调用其回调.
关于javascript - 理解 Promise 中的 .catch 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62961614/