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

185
Vistas
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 Respuestas
Responde la pregunta

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