Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

87
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda