简体   繁体   中英

declare promise type in typescript of a function

I saw this code somewhere, just curious, why need to specify Promise in the return type? isn't the function return data which is an object? and what's the | null for | null for ?

const getSomething = async (
  id: string
): Promise<UserData | null> => {
  try {
    const { data } = await axios.get(
      `${API}/user?id=${id}`
    );
    return data;
  } catch (err) {
    if (err.response) {
      return err.response.data;
    }
    return null;
  }
};

Async functions always return Promises - that way, the asynchronous await s can be waited for inside the function, and the result can be used outside the function.

Here, the getSomething tries to retrieve data from an axios call. If the call succeeds, the data is just returned:

return data;

But if the call doesn't succeed, it'll return one of the following instead:

if (err.response) {
  return err.response.data;
}
return null;

If the axios call throws, and there is no err.response property, then null will be returned. If you left out the | null | null , the getSomething function wouldn't be typed properly.

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