Should I return X in async functions, or should I return "Promise.Resolve(X)"?

I've always found this to be a tricky concept to fully grasp.

Let's delve into async functions in Typescript. Which implementation is accurate?

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;
}

Furthermore, let's imagine we're utilizing these functions and require the response for further processing within our application. Should we await the first function, the second function, both, or neither?

Answer №1

It's important to note that async functions always return a promise. Even if a plain return value is used, it will be wrapped with a resolved promise every time. The following code demonstrates how the same result can be achieved using either await or Promise.then.

(async function() {

   async function asyncFunctionTwo() {
      return 999;
   }


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

})();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to locate 'reflect-metadata' module within Docker container on Production Server

I encountered an error: module.js:550 throw err; ^ Error: Cannot find module 'reflect-metadata' at Function.Module._resolveFilename (module.js:548:15) at Function.Module._load (module.js:475:25) at Module.require ( ...

Stopping the papaparse streaming process once a certain number of results have been achieved

Currently, I am utilizing the PapaParse library to parse a large CSV file in chunk mode. During my data validation process, I encountered an issue where I was unable to stop streaming the data once validation failed. I attempted to halt the streaming by ...

Is it possible to add to the existing class based on a certain condition?

I have a coding challenge that I need help with. I have a set of code where I want to replace the old value in a class named "content" based on certain conditions. If the value within the class matches one of the values in an Array, then I need to append s ...

What steps can be taken for TypeScript to identify unsafe destructuring situations?

When working with TypeScript, it's important to prevent unsafe destructuring code that can lead to runtime errors. In the example below, trying to destructure undefined can cause a destructuring error. How can we ensure TypeScript does not compile suc ...

Changing the time in Angular while converting a string to a date object has proven to be

Can anyone help me with a problem I'm having trying to convert a String into a Date object without it being affected by timezone changes? Specifically, when I receive 2020-07-14T15:27:39Z from an http get request, I need to convert this into a Date o ...

A guide on calculating the number of days between two dates using Angular 12

I am currently utilizing Angular 12 for my project. The calculation of days based on two dates seems to be working perfectly fine in Chrome, but unfortunately, it fails in Firefox. In my TypeScript file: getDaysCount(firstDate: any, secondDate: any) { ...

Personalize the loading bar using JavaScript

Currently, I am utilizing a basic progress bar from Bootstrap. However, I have the desire to design a custom progress bar similar to this: Unfortunately, I am uncertain about how to create such a unique progress bar. Perhaps there is an existing JavaScri ...

Testing the ControllerAs syntax when dealing with forms in AngularJS

I am currently facing a situation with Angular that has left me quite puzzled. Controller function Controller () { // form used in template this.form ... } Template containing a form and utilizing the above controller Template <div ng-contr ...

Missing Component when Nested within Route in React Router v6

While incorporating the ChoosePlayer component within a Route using React Router v6, <BrowserRouter> <Routes> <Route path="/" element={<Home />} /> <Route path="/players"> <Route element ...

Updating Vue component property when Vuex store state changes: A step-by-step guide

As I work on developing a straightforward presentation tool using Vue js and Vuex to manage the app state, I am facing a challenge in implementing a feature that tracks changes in the presentation such as title modifications or slide additions/removals. Cu ...

Will a JavaScript source map file continue to function properly even after the source code file has been minified?

My experience I specialize in utilizing TypeScript and Visual Studio to transform highly organized code into functional JavaScript. My skills involve configuring the project and Visual Studio to perform various tasks: Merging multiple compiled JavaScrip ...

Unable to perform navigation during page load in a React.js application

I attempted to navigate to a route that should redirect the user back to the homepage when postOperations isn't set in the localStorage. To save time, please review the code snippet focusing on the useEffect and the first component inside return(). im ...

Customizing the items-per-page selection in the v-data-table component with Vuetify

I have a data table component footer with a select option that I want to update the values of. Can anyone guide me on how to achieve this? Is there a way to customize the numbers in the select option? https://i.sstatic.net/I5HCA.png ...

Next.js experiences slowdown when initializing props on the server side

I've been working on implementing SSR with Next.js. In my code, I'm fetching JSON data and using them as initial props. Everything works fine in development mode, but when I deploy to the server, fetching only works on the client-side (when navi ...

Guide on automatically attaching a file to an input file type field from a database

Currently, I am implementing a PHP file attachment feature to upload files. Upon successful upload, the system stores the filename with its respective extension in the database. The issue arises when trying to retrieve and display all entries from the ...

Unable to employ the .some() method with an array consisting of objects

I am currently attempting to determine whether my array of objects contains an attribute with a specific value. I wanted to use the array.some() method instead of a foreach loop, but I keep encountering an error: Error TS2345: Argument of type '(ele ...

What is the best way to trigger an ajax request when a user selects a tab?

How can I trigger an ajax call when a tab is clicked by the user? What is the best way to handle the HTML response and display it within the tab? How do I bind JavaScript events to the dynamically loaded HTML content? I am familiar with using jQueryUI tab ...

Merging Objects and inserting them into an array - Harnessing the power of JavaScript and

Having various objects stored in an array, each with a unique labelId assigned to them. Whenever there are matching label ids, the goal is to merge these objects together by consolidating some values inside a new combined object array. [ { fi ...

Creating a basic bar graph using d3.js with an array of input data

In my dataset, I have an array of form data that includes items like 'Male', 'Female', 'Prefer Not To Say'. I want to create a simple bar chart generator using D3.js that can display the percentages or counts of each item in t ...

My AJAX request seems to be redirecting to my PHP file instead of simply returning the response text. What could be causing this issue?

I am currently working on a project for my Web Engineering course and I am incorporating jQuery to execute an AJAX request to my PHP file using the POST method. The task specifies that "each time the [submit] button is pressed, the form data should be disp ...