2017-06-21 115 views
3

我知道問題很普遍。我正在使用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 

我知道,我能趕上無所作爲,而是誒。我也可以在我的API層做歷史推動的事情,但這不是它的責任。

如何避免我的控制檯中的錯誤?有沒有辦法?我甚至想過要這樣離開它。

+0

它是一個錯誤或警告? –

+0

它被顯示爲一個錯誤,但它是一個警告,因爲它不會破壞任何東西。我討厭在我的控制檯發出警告/錯誤,不會從我那裏傳出。這是不合理的,因爲它不是不好的做法imho – Nevosis

+1

也許你自己的代碼? * errorUtils.dispatchErrorWithTimeout(errorLogin); log.log(err); * –

回答

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

其實只是返回loginDaoCall工作正常。我真的沒有什麼不同,因爲它看起來像是同一個實例,但可能不是。 – Nevosis

0

這聽起來像你在你的catch塊有一個錯誤。當引發錯誤時,沒有第二個catch塊捕獲第1個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) 
}); 
相關問題