Other external function being executed while await waits for promise in "inner" function
Hello, I have a question when it comes to JS returning
promises, more specifically with async and await.
Consider these code:
start is a function that "runs" our app. My question is when we await inside our fetchProducts() that is we are waiting for the promise to be resolved, inside start(), does execution shifts to checkNumberOfProduct() even though fetchProducts() hasn't been completed? If so, can someone explain why pls.4 Replies
This is because of scope.
Your
fetchProducts function is awaiting somthingThatReturnsAPromise
But that's only within the scope of fetchProducts
Your start function doesn't know anything about what's going on inside the fetchProducts function it just sees that it needs to execute two functions.
You will need to await the fetchProducts inside start function too.
All async functions return a promise so they can also be awaitedoh ok I see
yep make sense, ty !
You can think of
async and being "contagious" or "insidious" (depending on how you view that keyword 😉 ).
Anything that touches an async function must be declared async as well otherwise it won't be able to await the result! And if you miss one await in the chain…you're screwed 🤣
For this reason I suggest not nesting async code if you can avoid it. One, maybe two calls deep is the max I recommend, anything else might be a code smell (as it's trying to do too much). Break those deeply-nested async calls into smaller functions to flatten the nesting.Yepp noted, thanks !