File1.ts: estoy llamando al siguiente método del servicio file2 y esperando la respuesta.
const output = await this.file2Service.getMainData();File2.ts: espero el valor de retorno (fuente de datos) del método a continuación. Pero lo que sucede aquí es "La siguiente función devuelve el origen de datos incluso antes de que se ejecute el código en el bloque .then()".
Así que me estoy volviendo indefinido cada vez. Qué se debe hacer para obtener el valor real de la fuente de datos.
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; }Ignore los errores de sintaxis en el fragmento anterior. Es solo un ejemplo, no el código real.
No necesita invocar .then si ya está esperando un método.
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.'); }