我知道这个问题很常见。我正在使用 es6 Promise,并且我有多个层。 在运行时,当我没有兑现承诺时,我的控制台中会出现
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 层中进行历史推送,但这不是它的责任。
如何避免控制台中出现错误?有办法吗?我什至想就这样离开吧。
你的问题是你正在
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");
}
});
听起来您的 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)
});
这个答案适用于那些使用
async
和 await
以及 try
和 catch
的人,在可能引发错误的承诺返回调用之前包含 await
关键字至关重要。在OP提供的示例中,相关函数是loginDao.login(...)
。
async function foo() {
try {
await yourAsyncFunctionThatErrorsOut()
// ^^ This await keyword is necessary to catch the error
// thrown by your promise-returning call yourAsyncFunctionThatErrorsOut()
} catch (error) {
console.log(error)
}
}