1

我正在使用 reactjs 开发一个应用程序,它可以让人们发布一些带有主题标签、提及和媒体的帖子。我开始在数据库中保存帖子,经过大量控制后,如果发生错误,我需要从数据库中删除帖子。这里是带有 promises 和 catch 块的函数:

        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) )

            })

现在的问题是,当我在 postHashtagRoutine() 中调用拒绝时,如果某些主题标签包含停用词,则不会调用 catch 块,并且不会执行控制台日志和 removePost() 函数。

这是我在 postHashtagRoutine() 中调用拒绝的代码部分

     Promise.all(promisesCheckStopwords)
                 .then( () => {
                   if ( stopwordsId.length > 0){
                        reject("stopwordsId in post");
                   }
                 })
4

1 回答 1

1

您可以throwThenable处理程序内部拒绝。

如果函数抛出错误或返回被拒绝的 Promise,则 then 调用将返回被拒绝的 Promise。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then

我建议使用throw <result>而不是reject([result]).

例如:

throw "stopwordsId in post"

我还建议您返回第二个电话以connectDb()确保承诺链链接在一起。

如果 onFulfilled 返回一个 Promise,则 then 的返回值将被 Promise 解析/拒绝。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then

第一个代码块:

    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 )

        })

第二个代码块:

     Promise.all(promisesCheckStopwords)
             .then( () => {
               if ( stopwordsId.length > 0){
                    throw "stopwordsId in post"
               }
             })
于 2019-07-10T11:34:26.387 回答