skip to Main Content

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


  1. 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);
        }
    }
    
    Login or Signup to reply.
  2. in #2, before the final statement setTypes(..), it jumps back to the parent

    That’s correct. As soon as an async function hits its first await, it returns a promise back to the parent. Some time later the function will resume and continue executing. If the function eventually reaches a return (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.

    if(response){
      await addType(response);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search