• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

158
Views
In async functions, do we return X, or do we return "Promise.Resolve(X)"?

This is something I have never quite been able to nail down.

Consider an async function in Typescript. Which is correct?

async function asyncFunctionOne(string1: string, string2: string, string3: string) {
    var returnObject1 = new object {
        fieldOne: object1,
        fieldTwo: object2,
        fieldThree: object3
    }

    return Promise.resolve(returnObject1)
}

async function asyncFunctionTwo(string1: string, string2: string, string3: string) {
    var returnObject2 = new object {
        fieldOne: object1,
        fieldTwo: object2,
        fieldThree: object3
    }

    return returnObject2;
}

Additionally, consider we were calling this function and we needed the response for something further in our program. Would we need to await the first function, the second function, both, or neither?

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

0

That async functions always return a promise. A plain return value will be wrapped with a resolved promise always. Observe in the following code that the same result can be obtained either using await or Promise.then.

(async function() {

   async function asyncFunctionTwo() {
      return 999;
   }


   asyncFunctionTwo().then((val => console.log(val)));
   
   //OR
   
   console.log(await asyncFunctionTwo())

})();

about 3 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 Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error