我将 JavaScript Promise 对象与 then()、catch() 一起使用。
无论 API 的响应如何(“STATUS_SUCCESS”或“STATUS_FAILED”),catch() 方法中的 console.log 始终运行。
这是 Promise 中的正常行为还是有办法仅在响应失败时才调用 catch() 方法?
更新了实例:
sendAccountDataToBackend(response) {
const { formData } = response;
const requestObj = {
url: 'http://localhost:3000/api/validate',
data: {
firstname: 'dummy_firstname',
lastname: 'dummy_lastname',
email: 'dummyemail'
}
};
let p = new Promise((resolve, reject) => {
account.Utils.globalAjaxRequest(requestObj, (success) => {
if(success.status === 'STATUS_SUCCESS') {
resolve();
console.log('resolved: ', p)
} else {
reject();
console.log('rejected: ', p);
}
});
})
p.then(() => {
console.log('Then: ', response);
}).catch(() => {
console.log('catch:', response);
})
}
最佳答案
您可以通过打印来找到引发错误的确切原因。
将您的 catch 处理程序更改为如下所示:
catch((e) => {
console.log('Catch', e);
})
除了“Catch”之外,您还会在控制台中看到错误的描述。
关于javascript - 为什么我的 Promise 总是命中 catch() 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57869060/