简体   繁体   English

如何将承诺转换为异步等待

[英]How do I convert promises to async await

login() {
    return new Promise((resolve, reject) => {
        userCollection.findOne({email: this.data.email}).then((myUser)=>{
            if (myUser && myUser.password == this.data.password) {
                resolve("Congrats! Successfully logged in");
            } else{
                reject("Login failed");
            }
        }).catch(()=>{
            reject("Please try again later")
        })
    })
}

This is my model and I can use it to find data from Mongodb .这是我的 model ,我可以用它从Mongodb中查找数据。 I'm using express js.我正在使用快递 js。 But, I want to know how I can use async await to do exactly the same thing that the above promise does.但是,我想知道如何使用async await来做与上述 promise 完全相同的事情。 I mean, I would like to convert this code to async await way.我的意思是,我想将此代码转换为async await方式。

Any assistance would be highly appreciated.任何帮助将不胜感激。

This should suffice:这应该足够了:

async function login() {
   try {
      const user = await userCollection.findOne({ email: this.data.email });

      if (user && user.password === this.data.password) {
         // handle valid user
      }
      else {
         // handle not found user or password mismatch
      }
   }
   catch (error) {
      // handle or rethrow error
   }
}

Duplicating your case will result in:复制您的案例将导致:

async function login() {
   try {
      const user = await userCollection.findOne({ email: this.data.email });

      if (user && user.password === this.data.password) {
         return 'Congrats! Successfully logged in';
      }
      else {         
         throw new Error('Login failed');
      }
   }
   catch (error) {
      throw new Error('Please try again later');
   }
}

Then in your caller code you can await (or .then() it, but prefer await ) the result of login:然后在您的调用者代码中,您可以await (或.then()它,但更喜欢await )登录结果:

try {
   const loginResult = await login();
}
catch(error) {
   // handle error
}

Note that in doing so, you will once again need to mark the caller function as async for you to be able to use the await operator.请注意,这样做时,您将再次需要将调用方 function 标记为async ,以便您能够使用await运算符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM