manju4ever manju4ever - 1 month ago 6
Javascript Question

async/await throwing error in es2015

Async/ Await throwing error while compilation. Im currently using babel with presets - es2015, & plugin - transform-async-to-generator. Check my code below

async function verifyUserAlreadyExists(phone, email) {
try {
db.collection("users").find({
$or:{"contact_details.phone": phone, "contact_details.email": email}
}, (err, cursor)=>{
await cursor.count() >= 1;
});
}catch(err) {
console.log("Verify User Exists:"+JSON.stringify(err));
}
}

export default {
getAllUsers: (request, reply) => {
db.collection("users").find({}).toArray((err, users) => {
reply(users);
});
},
insertNewUser: (request,reply) => {
let userAlreadyExists = await verifyUserAlreadyExists("7259769413");
console.log(userAlreadyExists);
}
}


I'm getting the following error

the error i see

Answer

Since the MongoDB driver returns promises for all async functions, you can should rewrite your code so it doesn't use callbacks at all:

async function verifyUserAlreadyExists(phone, email) {
  try {
    let cursor = db.collection("users").find({
      $or : {
        "contact_details.phone" : phone,
        "contact_details.email" : email
      }
    });
    return await cursor.count() >= 1;
  } catch(err) {
    console.log("Verify User Exists:"+JSON.stringify(err));
    return false;
  }
}

export default {
  getAllUsers: async (request, reply) => {
    return await db.collection("users").find({}).toArray();
  },
  insertNewUser: async (request,reply) => {
    let userAlreadyExists = await verifyUserAlreadyExists("7259769413");
    console.log(userAlreadyExists);
    return userAlreadyExists;
  }
}