Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

86
Vistas
Return type for asynchronous function

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).

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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);
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda