[英]What is the good way to break from promise chain?
我想知道如何在JS中正確打破Promise鏈。
在這段代碼中,我首先連接到數據庫,然后檢查集合是否已經有一些數據,如果沒有添加它們。 不要注意一些actionhero.js代碼..這沒關系。
主要問題是: 可以使用throw null打破鏈條嗎?
mongoose.connect(api.config.mongo.connectionURL, {})
.then(() => {
return api.mongo.City.count();
})
.then(count => {
if (count !== 0) {
console.log(`Amout of cities is ${count}`);
throw null; // break from chain method. Is it okay ?
}
return api.mongo.City.addCities(api.config.mongo.dataPath + '/cities.json');
})
.then(cities => {
console.log("Cities has been added");
console.log(cities);
next();
})
.catch(err => {
next(err);
})
非常感謝!
盡管它看起來像是一個巧妙的技巧,並且可以按您期望的那樣工作,但我還是建議您不要拋出非錯誤對象。
如果您拋出一個實際的Error並明確地處理它,那么其他維護該代碼的開發人員將更容易預測。
Promise
.resolve()
.then(() => {
throw new Error('Already in database');
})
.catch(err => {
if (err.message === 'Already in database') {
// do nothing
} else {
next(err);
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.