拒绝后在catch块中查询

时间:2019-07-10 11:17:22

标签: node.js aws-lambda claudiajs

我正在使用reactjs中的一个应用程序,该应用程序使人们可以发布带有主题标签,提及和媒体的帖子。我开始将帖子保存在db中,经过很多控制后,如果发生某些错误,我需要从数据库中删除帖子。这里带有promise和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()中调用reject时,如果某些主题标签包含停用词,则不会调用catch块,并且不会执行控制台日志和removePost()函数。

这是我在postHashtagRoutine()中称为拒绝的代码部分

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

1 个答案:

答案 0 :(得分:1)

您可以在throw处理程序内Thenable拒绝。

  

如果函数抛出错误或返回被拒绝的Promise,则调用将返回被拒绝的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"
               }
             })