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

102
Visualizações
Why does this aysnc function not implicitly return a promise?

I read in this Stack Overflow question async/await implicitly returns promise? that:

"An Async function will always return a promise. If you don't explicitly return a promise, the value you return will automatically be wrapped in a promise."

So why does my getData2() function below return undefined?

const getData = async() => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('this is the data');
    }, 2000);
  });
};

const getData2 = async() => {
  setTimeout(() => {
    return 'this is the data without an explicit promise';
  }, 1000);
};

(async() => {
  console.log(await getData2()); // DOES NOT WORK: displays 'undefined' immediately
  console.log(await getData()); // WORKS: waits one second and displays data
})();

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

getData2 is returning a Promise, but you're awaiting it, which extracts the resolve value from the Promise.

console.log(await getData2());

turns into

console.log(await promiseThatResolvesToUndefined);
console.log(undefined);

If you don't await it, you'll see the Promise.

const getData2 = async () => {
    setTimeout(() => {
        return 'this is the data without an explicit promise';
    }, 1000);
};

(async () => {
    console.log(getData2());
})();

The resolve value is undefined because nothing is being returned inside the body of getData2.

about 4 years ago · Juan Pablo Isaza Relatório

0

The issue is not with async but with using return inside an inner function (in this case a lambda), which returns from that inner function (not the outer function), and setTimeout then ignores that return value. The correct way to do this is getData (but without the async keyword which adds an second layer of Promise).

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