【问题标题】:NodeJS + mongoDB query after another : Promises/callbackNodeJS + mongoDB 又一个查询:Promises/callback
【发布时间】:2020-05-10 22:49:32
【问题描述】:

我有三个功能

A -> mongoDb 查询然后调用 B 然后调用 console.log("test")

B -> 设置一些规则并调用 C

C --> mongoDb 查询返回 A -> console.log("test")

我在异步/承诺方面遇到了困难,经过很长一段时间后,我找到了一个看起来不太优雅的可行解决方案。 (也许是因为我对 async/await 不是很熟悉) 我想知道是否有更好/更优雅/更易读的解决方案?

这里的代码只有“有用的部分”。 (console.logs 应该写 1,2,3,4,5,6。)

app.get('/searchWingding', (req,res)=>{
    users.findOneAndUpdate( mongoDBQuery
                                    {returnOriginal : false})
                        .then(async () =>{  
                            //remove unnecessary code for issue
                                console.log(1)                                  
                                await wingdingsExhibitionRule(users,player, allWingdings)
                                console.log(6)
                            })})

async function wingdingsExhibitionRule(users,player, wingdingsList){
        //remove unnecessary code for issue
        console.log(2)                                  
    await changePlayerUnlock(users,player,"wingdingsExhibition")
    console.log(5)                                  
}

async function changePlayerUnlock(users,player,unlockRule){
    //remove unnecessary code for issue
    console.log(3)
const a = users.findOneAndUpdate(mongoDBQuery,
                        {returnOriginal : false})
.then(()=>{                 
                            console.log(4)
                            if(!checkStringInArray(player.unlock,unlockRule)){
                            player.unlock.push(unlockRule)
                            }
                        })
await a
}
```

【问题讨论】:

    标签: node.js mongodb async-await


    【解决方案1】:

    您正在使用async-await 语法以及承诺。您的代码可以编写如下所示,仅使用 async-await 语法

    app.get('/searchWingding', async (req,res)=> {
          await users.findOneAndUpdate()
          console.log(1)
          await wingdingsExhibitionRule(users,player, allWingdings)
          console.log(6)
    
    async function wingdingsExhibitionRule(users,player, wingdingsList){
         console.log(2)                                  
         await changePlayerUnlock(users,player,"wingdingsExhibition")
         console.log(5)                                  
    }
    
    async function changePlayerUnlock(users,player,unlockRule) {
        console.log(3)
        const a = await users.findOneAndUpdate()
        console.log(4)
    }
    

    【讨论】:

    • 非常感谢,这样更有意义!
    • 我正在更改我的整体代码以删除所有承诺,它更加清晰。非常感谢您的帮助!
    猜你喜欢
    • 2019-01-06
    • 2015-01-08
    • 1970-01-01
    • 2020-03-25
    • 2015-07-25
    • 1970-01-01
    • 2012-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多