Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

'await' in nested sub-function does not wait, only top-level function's 'await' waits

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading