简体   繁体   中英

Callback Async function inside async function ! Is correct?

I expect this reuse async function use many places !

const requestGetData = (callback?: Function): void => {
      (async (): Promise<void> => {
        try {
          if (callback) {
            await callback();
          }
          const data = await getDataApi();
          setData(data);
        } catch (error) {
          console.log(error)
        }
      })();
  };

I have different async function :

  const requestUpdateData = async (): Promise<void> => {
      await postUpdate();
      setCountUpdate(count+1);
    };

I will use :

...
const handleUpdate=()=>{
  requestGetData(requestUpdateData);
}

useEffect(()=>{
  requestGetData()
},[])

I customize async is correct? Is there a better way ? I want reuse function requestGetData

Considering when you call the function, you call it with await , which means you always expect the callback function to be async. I would suggest updating the type declaration for the callback parameter to () => Promise<any> and I don't see why this needs to be an IIFE. Otherwise, it looks fine to me.

There's no need to wrap it inside an IIFE, and there's also no need to note the types of a function that TS can infer automatically. In addition, rather than Function , better to use a more specific type, like () => void .

Consider something like the following:

const requestGetData = async (callback?: () => void) => {
    try {
        if (callback) {
            await callback();
        }
        setData(await getDataApi());
    } catch (error) {
        console.log(error);
    }
};

Another option would be to remove the callback completely, and have the caller chain a .then onto the requestUpdateData call:

const requestGetData = () => {
    return getDataApi().then(setData);
};
requestUpdateData()
    .then(requestGetData)
    .catch((error) => {
        console.log(error);
    });

Above, requestGetData returns its Promise chain without catching, but you can catch inside it if you want if nothing else in the app needs special logic when it encounters an error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM