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?
>Solution :
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
const fetchData = async (referralId:string) => {
const response = await get<any>("/service-request/" + referralId + "/null");
if(response){
// add await here
await addType(response);
}
}