Javascript 未兑现(承诺)

Javascript 未兑现(承诺),javascript,reactjs,promise,Javascript,Reactjs,Promise,我知道这个问题很常见。我使用es6承诺,我有多个层次。 在运行时,当我没有得到承诺时,我的控制台中有Uncaught(in promise)。但事实是,我确实在代码中捕捉到了它 快速简化示例: LoginApi.js var loginDaoCall = loginDao.login(username, password); loginDaoCall .then(function (res) { store.dispatch(loginSuccess());

我知道这个问题很常见。我使用es6承诺,我有多个层次。 在运行时,当我没有得到承诺时,我的控制台中有
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
loginApi.login(用户,密码)。然后(()=>{
//在此处更改,而不是在呈现中更改,以便用户可以返回登录页面
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)
});

您的问题是,您返回的是被拒绝的
loginDaoCall
,而不是已处理错误的承诺
loginApi.login(用户、密码)
确实返回了一个被拒绝的承诺,即使在另一个分支中处理了该承诺,由进一步的
.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


它是一个错误还是一个警告?它显示为一个错误,但它是一个警告,因为它不会破坏任何东西。我讨厌控制台中没有来自我的警告/错误。这是不合理的,因为这不是一种不好的做法。你有自己的代码吗?errorUtils.dispatchErrorWithTimeout(errorLogin);log.log(err);不,事实是,这是一个“未处理的拒绝”,如果我在我的loginContainer中捕捉到被拒绝的承诺,我没有错误消息。这是一个控制台。错误来自es6-promises。您的捕获中没有抛出错误吗?这是什么错误?实际上,只需返回loginDaoCall就可以了。我真的不明白有什么不同,因为它看起来像是同一个例子,但可能不是。
// 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");
    }
});