I have the following code:
let id=null;
tokenModel.findOne({ tokens: { "$in" : [token]} }).then((_token)=>
{
if (_token)
id = _token._id
else
id = 0
}).catch((err) => {
console.log("tokenModel Error ", err)
})
const data = new userModel({
token: id
});
data.save().then(() =>
{
res.json({"id": id})
}
I want to wait for tokenModel.findOne() to finish before proceeding with the rest of the code. As for now, userData.save() writes id=null
instead of =0 or = _token._id
(because promise have not ended yet).
I could move everything inside .then() of findOne function but that would decrease readability and I really want to avoid that.
I have tried making the whole function as async, and then adding await:
await tokenModel.findOne({ tokens: { "$in" : [token]} }).then((_token)=>
{
if (_token)
id = _token._id
else
id = 0
}).catch((err) => {
console.log("tokenModel Error ", err)
})
but to no avail.