-2

Simple question, lets pretend I have a function like this (In this example it's within a class, using an automation framework):

async logout() {
    await this.page.click('#logout');
}

and then call it in another file via

await new LogoutPage(driver).logout()

Do I really need the second await? Similarly if we return something with await IE:

async LoggedOut(): Promise<boolean> {
    return await isVisible('#logged_out_logo');
}

Would I need an await also when calling that?

Barmar
  • 741,623
  • 53
  • 500
  • 612
msmith1114
  • 2,717
  • 3
  • 33
  • 84
  • 1
    If you don't use the second `await`, then you won't wait. – Barmar Aug 28 '23 at 19:49
  • You would have to write `new LogoutPage(driver).logout().then(() => { code that runs after logout })` – Barmar Aug 28 '23 at 19:50
  • 1
    Why are you using `async` and `await` in the `logout()` function in the first place? Does `click()` return a promise that you can wait for? – Barmar Aug 28 '23 at 19:52
  • What happens when you try and test it? You only *need* `await` (or a `.then()` callback) if you want to await the result of the asynchronous operation. That's not always the case. – David Aug 28 '23 at 20:08

1 Answers1

1

Yes, you need the second await. See what happens when you remove the first await

async function LoggedOut(): Promise<boolean> {
    return isVisible('#logged_out_logo');
}

Then, you may the remove async

function LoggedOut(): Promise<boolean> {
    return isVisible('#logged_out_logo');
}

You see, the return type will remain Promise<>. async/await is pretty much syntactic sugar to avoid promises inside the function.

Thus, to the caller, that is still a promise which needs to be awaited...

await new LogoutPage(driver).logout()
// continue

or "thened"

new LogoutPage(driver).logout().then(() => {
  // continue
})
Tomasz Pluskiewicz
  • 3,622
  • 1
  • 19
  • 42
  • I guess im confused or maybe made the question not understandable. Why do we need an await calling the function if inside the function there is already an await – msmith1114 Aug 29 '23 at 13:06
  • Because `await` inside is more or less syntactic sugar for a promise. Either way, `LoggedOut` function is async and returns a `Promise`. Because it is async, the caller still needs to await – Tomasz Pluskiewicz Aug 30 '23 at 11:38
  • That makes sense. thanks – msmith1114 Aug 30 '23 at 13:15