【发布时间】: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