Home > Software design >  Benefits of using async await in simple functions
Benefits of using async await in simple functions

Time:07-19

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:

"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.

CodePudding user response:

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.

CodePudding user response:

Doesn't this mean JS Engine automatically waits and behaves just the same like using async? That would make it redundant.

No, the JS engine doesn't automatically "wait". Without await it would immediately continue executing the if statements, which obviously is not desired, as then you would not have the actual user object to work with, but "just" a promise object.

If the only thing that you wanted to do was to call fetch then it would be redundant to await it, but since you need the response from that request, you need to get informed when that response is available, and that is what await is offering you. You could alternatively chain a then call, whose callback would be called when the response becomes available.

  • Related