gpt4 book ai didi

javascript - 未捕获(在 promise 中)

转载 作者:数据小太阳 更新时间:2023-10-29 04:47:15 24 4
gpt4 key购买 nike

我知道这个问题很常见。我正在使用 es6 promises,并且我有多个层。在运行时,当我没有捕捉到 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;

登录容器.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 层中执行历史推送,但这不是它的职责。

如何避免控制台中的错误?有办法吗?我什至在考虑就这样离开。

最佳答案

您的问题是您返回被拒绝的loginDaoCall,而不是错误已被处理的 promise 。 loginApi.login(user, password) 确实返回了一个被拒绝的 promise ,即使在另一个分支中处理了该 promise ,进一步的 .then() 返回的 promise 确实也被拒绝,没有处理。

你可能想做类似的事情

// 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");
}
});

关于javascript - 未捕获(在 promise 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44678505/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com