JANATI MOHAMMED
JANATI MOHAMMED

Reputation: 73

mongoose findOne : different between async & sync

I have confuse with know what is different between :

var users = Users.findOne({key})

var users = await Users.findOne({key})

Upvotes: 1

Views: 337

Answers (1)

Shubham Dixit
Shubham Dixit

Reputation: 1

var users = Users.findOne({key})

Users.findOne() method returns a promise which can either be resolved or rejected. See promises

So in above case users variable actually contains a promise object and if you want to get the resolved data you have to do something like

users.then(data=>{
// your db query data
}).catch(err=>{
// error if something goes wrong
})



    

The below syntax with await actually gives you the resolved data of promise see await

 var users = await Users.findOne({key})

so you will have data like this [{key:value}] of your mongodb stored in users variable.

Also await is valid only in async function so you need to wrap it inside async function

async function foo(){
    var users = await Users.findOne({key})

}

Upvotes: 1

Related Questions