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

83
Views
Return type for asynchronous function

I have this code that is a simple implementation of async/await while doing ajax call

export const getExternalResource = async (): Promise|String|null => {
    return new Promise(async (resolve, reject) =>{
        const response = await fetch(url);
        const json = response.json();

        if(json) {
            resolve(json);
        } else {
            resolve(null)
        }
    });
};

/**
 * @var resource will be null|string
 */
const resource = await getExternalResource();

My question is what is the correct return type for the getExternalResource() function?

In code it returns a promise, however when calling the function with await keyword, it returns a basic data type (string|null).

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You dont need a fetch inside a Promise since fetch returns a promise. Also return type of an async function or method must be the global Promise type. So changed the return type here to Promise<any>. You can replace any with the matching type

export const getExternalResource = async(url: string): Promise<any> => {
  return await fetch(url).then(response => response.json());
};
const resource = getExternalResource('url').then(d=>d);
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!