在es2015中异步/等待抛出错误

时间:2016-10-31 18:53:30

标签: javascript ecmascript-6 babeljs

编译时异步/等待抛出错误。我目前正在使用预设的babel - es2015,&插件 - transform-async-to-generator。检查下面的代码

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);
    }   
}

1 个答案:

答案 0 :(得分:3)

由于MongoDB驱动程序为所有异步函数返回promise,因此可以重写代码,因此它根本不使用回调:

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;
  }
}