我知道这个问题很平常。我正在使用es6 promises,而且我有多个层。
在运行时,当我没有捕获承诺时,我在控制台中有Uncaught (in promise)
。但事实是我的代码确实降低了。
快速简化示例:
LoginApi.js
var loginDaoCall = loginDao.login(username, password);
loginDaoCall
.then(function (res) {
store.dispatch(loginSuccess());
log.log("[loginApi.login] END");
})
.catch(function (err) {
store.dispatch(loginFail());
errorUtils.dispatchErrorWithTimeout(errorLogin);
log.log(err);
});
return loginDaoCall;
loginContainer.js
loginApi.login(user, password).then(() => {
// Change here instead of in render so the user can go back to login page
this.props.history.push(baseUrlRouter + "test");
}); // <- Error here cause I don't CATCH the promise, but I do catch it in my loginapi.js
我知道我什么也做不了,但是呃。我也可以在我的API层执行历史推送工作,但这不是它的责任。
如何在控制台中避免错误?有办法吗?我甚至想把它留下来。
答案 0 :(得分:1)
听起来你的catch块有错误。抛出错误时,没有第二个catch块来捕获第一个catch块中的错误。
修复它......
.then(function (res) {
// some code that throws an error
})
.catch(function (err) {
// some code that throws an error
})
.catch(function (err) {
// This will fix your error since you are now handling the error thrown by your first catch block
console.log(err.message)
});
答案 1 :(得分:1)
您的问题是您return
拒绝了loginDaoCall
,而不是已经处理错误的承诺。 loginApi.login(user, password)
确实返回了被拒绝的承诺,即使在另一个分支中处理了这个承诺,进一步.then()
返回的承诺也会被拒绝并且没有被处理。
您可能想要执行类似
的操作// LoginApi.js
return loginDao.login(username, password).then(function (res) {
store.dispatch(loginSuccess());
log.log("[loginApi.login] END");
return true;
}, function (err) {
store.dispatch(loginFail());
errorUtils.dispatchErrorWithTimeout(errorLogin);
log.log(err);
return false;
}); // never supposed to reject
// loginContainer.js
loginApi.login(user, password).then(success => {
if (success) {
// Change here instead of in render so the user can go back to login page
this.props.history.push(baseUrlRouter + "test");
}
});