I'm working on an application in reactjs that let people publish some post with hashtags, mentions and media. I start saving post in db, after a lot of controls I need to remove the post from DB if some error happen. Here the functions with the promises and the catch block:
connectDb()
.then( () => { return savePost() } )
.then( () => { return postHashtagRoutine() } )
.then( () => { return iteratePostMedia() } )
.then( () => { return detectLanguage() } )
.then( () => { return updatePost() } )
.then( () => { console.log("pre conn release") } )
.then( () => { conn.release() } )
.then( () => { resolve( { success : "done" } )
.catch( (err) => {
connectDb()
.then( () => { console.log("create post error", err) } )
.then( () => { return removePost() } )
.then( reject(err) )
})
Now the problem is that when I call reject in postHashtagRoutine(), if some hashtag contains stopwords, the catch block isn't called and the console log and the removePost() function aren't executed.
Here the code portion where I call the reject in postHashtagRoutine()
Promise.all(promisesCheckStopwords)
.then( () => {
if ( stopwordsId.length > 0){
reject("stopwordsId in post");
}
})
You can throw
inside a Thenable
handler to reject.
A then call will return a rejected promise if the function throws an error or returns a rejected Promise.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
I would suggest using throw <result>
instead of reject([result])
.
For example:
throw "stopwordsId in post"
I'd also suggest you return the second call to connectDb()
to ensure that the promise chains are linked together.
If onFulfilled returns a promise, the return value of then will be resolved/rejected by the promise.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
First Code Block:
connectDb()
.then( () => { return savePost() } )
.then( () => { return postHashtagRoutine() } )
.then( () => { return iteratePostMedia() } )
.then( () => { return detectLanguage() } )
.then( () => { return updatePost() } )
.then( () => { console.log("pre conn release") } )
.then( () => { conn.release() } )
.then( () => { return { success : "done" } )
.catch( (err) => {
return connectDb()
.then( () => { console.log("create post error", err) } )
.then( () => { return removePost() } )
.then( throw err )
})
Second Code Block:
Promise.all(promisesCheckStopwords)
.then( () => {
if ( stopwordsId.length > 0){
throw "stopwordsId in post"
}
})