When Not To Use Async Await
For example when we have to call 2 apis, we do something like this:
const user = await getUserById(id);
const products = await getProducts();
return { user, products };
However, this is actually bad as we need to call the getUserById()
first before calling the getProducts()
and this make it less optimal
[!note]
Callingawait
will block the next call of the same async function.
Whereas we could've do these calls in concurrent because they're not dependent on eachother.
const [user, products] = await Promise.all([
getUserById(id),
getProducts()
])
return { user, products }
[!note]
Note thatPromise.all
is fail-fast — which means if there is 1 promise that rejects, it will stops the whole flowFor a fail-safe, we can consider
Promise.allSettled
[!important]
Javascript is single-threaded by nature so at a moment, only 1 task will be executing, although it will switch between all the promises which makes the execution appear to be concurrent but it not.To achieve real concurrent, we need to use worker threads