There is a thread on this which didn’t really answer my question and doesn’t offer any practical solutions.
I have a function that involves await
and, depending on a condition in the result, it calls a sub-function which likewise involves await
:
const fetchData = async (referralId:string) => {
const response = await get<any>("/service-request/" + referralId + "/null");
if(response){
addType(response);
}
}
const addType = async (response:any) => {
if (response['field'] === 'Y') {
// Additional fetch to set a new field into obj manually
let id = response['id'];
const list = await get<any>("/types/?id=" + id);
setTypes(list);
}
}
The debugger shows that in #1 the await blocks the function flow, but in #2, before the final statement setTypes(..)
, it jumps back to the parent. It comes back to that final statement later. So the await
doesn’t wait as it should. How would I fix this?
2
Answers
You need to know or remember that all async functions return a promise. So to make this work, you just need to await the returned promise
That’s correct. As soon as an
async
function hits its firstawait
, it returns a promise back to the parent. Some time later the function will resume and continue executing. If the function eventually reaches areturn
(implicit or explicit), this will cause the promise to resolve with the return value.If you want the parent to wait until the promise is resolved, the parent must
await
that promise.