Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

184
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!