Home > Software design >  Return type for asynchronous function
Return type for asynchronous function

Time:02-24

I have this code that is a simple implementation of async/await while doing ajax call

export const getExternalResource = async (): Promise|String|null => {
    return new Promise(async (resolve, reject) =>{
        const response = await fetch(url);
        const json = response.json();

        if(json) {
            resolve(json);
        } else {
            resolve(null)
        }
    });
};

/**
 * @var resource will be null|string
 */
const resource = await getExternalResource();

My question is what is the correct return type for the getExternalResource() function?

In code it returns a promise, however when calling the function with await keyword, it returns a basic data type (string|null).

CodePudding user response:

You dont need a fetch inside a Promise since fetch returns a promise. Also return type of an async function or method must be the global Promise type. So changed the return type here to Promise<any>. You can replace any with the matching type

export const getExternalResource = async(url: string): Promise<any> => {
  return await fetch(url).then(response => response.json());
};
const resource = getExternalResource('url').then(d=>d);
  • Related