Unprepared (in a promise)

I know the problem is common. I am using es6 promises and I have multiple layers. At runtime, when I don't understand the promises, I have Uncaught (in promise)

in my console. But the fact is, I will actually catch it in my code.

A quick simplified example:

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

      

I know I might not have caught anything, but, yes. I could also make history as far as the API layer is concerned, but that is not his responsibility.

How can I avoid the error in my console? Is there a way? I'm even considering leaving it that way.

+3


source to share


2 answers


Your problem is that you were return

with a rejected loginDaoCall

and not a promise when the error was already handled. loginApi.login(user, password)

did return a rejected promise, and even when it was processed in another branch, the promise returned by the further .then()

one is also rejected and not processed.

You might want to do something like

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

      

+1


source


It looks like you have an error in your catch block. When an error occurs, there is no second catch block to catch the error in the first catch block.

To fix this ...



.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)
});

      

0


source







All Articles