Reputation: 363
I am wondering how can I properly break promise chain in JS.
In this code, I am connecting to database at first, then I am checking if collection already has some data, if not add them. Don't pay attention to some actionhero.js code..it does not matter here.
The main question is: Is it okay to break chain using 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);
})
Many thanks!
Upvotes: 0
Views: 74
Reputation: 4266
Despite it may seem like a clever trick and will work as You expect, I would advise against throwing non-error objects.
It would be much more predictable for other developers that will maintain this code if You throw an actual Error and handle it explicitly.
Promise
.resolve()
.then(() => {
throw new Error('Already in database');
})
.catch(err => {
if (err.message === 'Already in database') {
// do nothing
} else {
next(err);
}
});
Upvotes: 2