Search code examples
javascriptangulartypescriptasync-awaites6-promise

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.


Solution

  • 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.');
    }