Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Benefits of using async await in simple functions

I have a simple function that aims to log a user in, and some guard clauses in it to rule out errors

 async signIn(email: string, passwort: string): Promise<void> {
    const user: IPerson = await this.fetchUser(email);
    if (user === undefined) {
      return Promise.reject('Wrong email');
    }
    if (user.passwort !== passwort) {
      return Promise.reject('Wrong password');
    }
    if (!this.logInUser(user)) {
      return Promise.reject('Login Failed');
    }
    return Promise.resolve();
  }

I used async await to wait for the promise resolve of fetchUser giving me the user, but this made me think, what benefits does await have here?

As summarized in some blog this is how async works:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"Let’s emphasize: await literally suspends the function execution until the promise settles, and then resumes it with the promise result. That doesn’t cost any CPU resources, because the JavaScript engine can do other jobs in the meantime: execute other scripts, handle events, etc."

But in my case, there is no other other jobs in the meantime, the function can only resolve if the fetchUser provides something. Doesnt this mean JS Engine automatically waits and behaves just the same like using async? That would make it redundant.

>Solution :

what benefits does await have here?

It lets you write syntax that is easier to follow than using then with a callback.

That’s all.


But in my case, there is no other other jobs in the meantime, the function can only resolve if the fetchUser provides something.

fetchUser is asynchronous. It isn’t made asynchronous by the use of await. It provides a promise.

If you don’t await that promise then you are just changing where the code execution is suspended.

Instead of signIn being suspended and the code that (you say) does nothing outside it continuing, you’ll instead only suspend fetchUser and signIn will continue processing with the promise returned by fetchUser instead of the User object that that promise eventually resolves with.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading