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

194
Visualizações
How to return the value resolved from promise in function?

File1.ts: I am calling the below method of file2 service and expecting the response.

const output = await this.file2Service.getMainData();

File2.ts: I am expecting the return value(dataSource) from the below method. But what's happening here is "The below function is returning the dataSource even before the code in .then() block gets executed."

So I am getting undefined every time. What needs to be done in order to get the actual dataSource value.

public async getMainData(): Promise<any> {
    const data = await this.getSubData();
  data.forEach((result) => {
    result.then((finalResult) => {
            if (finalResult === 'success') {
            const dataSource = await this.callDataSource();
        }
    });
  });
  return dataSource;

}

Please ignore the syntax errors in above snippet, Its just an example not the actual code.

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

0

You don't need to invoke .then if you're awaiting a method already.

public async getMainData(): Promise<any> {
  const data = await this.getSubData();

  for (const result of data) {
    // from your code sample it's unclear 
    // whether getSubData returns a collection of 
    // values or a collection of promises-of-values, 
    // remove the await if you're simply returning values
    
    const finalResult = await result;

    if (finalResult === 'success') {
      return await this.callDataSource();
    }
  }

  throw new Error('could not find a successful result.');
}
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