2

I wanted to have clarification on this. Let's say I have two functions. One is an async function. If I were to call that async function within another function, would that function call need the await keyword, and therefore the other function must also be an async function too?

That is my mindset of how I approach this. I haven't had any errors thrown before because of this.

1
  • 1
    You can use promises explicitly instead of await. Commented Sep 3, 2020 at 21:14

3 Answers 3

3

Would that function call need the await keyword, and therefore the other function must also be an async function too?

No. An async function is just a function that always returns a promise, and it's actually pretty indistinguishable from a normal function that returns a promise (from the outside).

The await keyword is not a modifier for the function call before which it is placed. It's just awaiting a promise value that the call is returning, and this works for any other expression. You can also split it apart like const promise = someFunction(); const result = await promise;.

Sign up to request clarification or add additional context in comments.

Comments

3

A function that uses the async keyword:

  • Will return a promise that resolves to the value that it returns
  • Supports the await keyword which will let it go to sleep until the promise on the right hand side of the await keyword resolves

So given:

function async foo() {
    return 27;
}

function bar() {
    const return_value = foo();
}

foo();

foo will return a promise which resolves to 27

The return_value variable will the value of a promise.

There is no requirement for bar to use the async keyword unless you want to change it to:

const return_value = await foo();

… so that bar can go to sleep until the promise returned by foo resolves to 27 (in which case return_value would be 27 instead of being a promise).

Comments

0

No your function that calls the asynch function won't getting through this asynch because the normal calculation goes on. Only the part which waits on the asynch function sleeps as long as it gets an answer from the asynch.

Otherwise the hole programm would stop and wait just on your asynch-answer and with this the asynch wouldn't function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.