我正在尋找更容易/更簡單的方式來創建錯誤功能,我只是尋找一種簡單的方法來退出承諾鏈。您可以在下面看到一個錯誤對象NoUserFound
和承諾鏈。我期待的結果是當model.readUserAddresses
返回false
我拋出一個特定的錯誤跳過承諾鏈。是否有更簡單更直接的(單行)方法來創建NoUserFound
自定義錯誤只是爲了這個目的?使用自定義錯誤退出/中斷承諾
function NoUserFound(value) {
Error.captureStackTrace(this);
this.value = value;
this.name = "NoUserFound";
}
NoUserFound.prototype = Object.create(Error.prototype);
model.readUserAddresses(email)
.then(ifFalseThrow(NoUserFound))
.then(prepDbCustomer)
.then(shopify.customerCreate)
.catch(NoUserFound,() => false)
理想情況下,我可以做這樣的事情。
model.readUserAddresses(email)
.then(ifFalseThrow('NoUserFound'))
.then(prepDbCustomer)
.then(shopify.customerCreate)
.catch('NoUserFound',() => false)
而不一定有一個無用的一次性錯誤類。
想一想,如果鏈條中的第一個承諾引發了實際的錯誤,這可能是最好的。 – ThomasReggi
即時通訊實現Promise in Native,但在[bluebird](https://github.com/petkaantonov/bluebird)中可以很好地實現,您可以在此處爲承諾 – kiro112
函數ifFalseThrow(e ){return function(v){if(!v)throw new Error(e)}}' – dandavis