Transform a Promise of string array into a regular string array

I have a function called fetchSavedCards that retrieves a list of saved cards. The function returns a Promise Object, but I want to convert it into an array of strings and return it. Is this possible?

const fetchSavedCards = (): string[] => {
return fetch("/fetchSavedCards")
    .catch((error: Error) => {
        throw new Error(error.message);
    })
    .then((response) => {
        return response.json();
    })
    .then((cards: string[]) => {
        return cards;
    });

};

After retrieving the result set, I need to display it on a web page. However, I've encountered an issue where the .map() function does not work with a Promise object.

    <CardContent>
    <label> Card Selection  </label>
    <div className="container" id="cards">
        {Service.fetchSavedCards().map(
            (card) => <label>
                <input type="radio" name="selectedCard" value="test" onChange={this.handleCardSelectionChange}/>
                    {card}
            </label>)}
    </div>
    ...
</CardContent>

Answer №1

Attempting to convert an async function into a synchronous one is not advisable and simply cannot be done. It seems like you may be struggling with using fetchSavedCards correctly after defining it as shown below.

const fetchSavedCards = (): Promise<string[]> => {
  return fetch("/fetchSavedCards")
    .then((response) => {
        return response.json();
    })
    .then((cards: string[]) => {
        return cards;
    })
    .catch((error: Error) => {
        throw new Error(error.message);
    });
};

// How to properly use fetchSavedCards
fetchSavedCards().then(cards => handleCards(cards));

By the way, it's recommended to place the .catch() at the end of your promise chain.

If you intend to utilize this data for rendering views in React, consider storing the retrieved data in the component's state and rendering based on that state.

Here is a full example using React hooks:


const fetchSavedCards = (): Promise<string[]> => {
  return fetch('/fetchSavedCards')
    .then(response => {
      return response.json()
    })
    .then((cards: string[]) => {
      return cards
    })
    .catch((error: Error) => {
      throw new Error(error.message)
    })
}

function Cards() {
  const [cards, setCards] = useState<string[]>([])

  useEffect(() => {
    fetchSavedCards().then(cards => setCards(cards))
  }, [])

  return (
    <CardContent>
      <label> Card Selection </label>
      <div className="container" id="cards">
        {cards.map(card => (
          <label>
            <input
              type="radio"
              name="selectedCard"
              value="test"
              onChange={this.handleCardSelectionChange}
            />
            {card}
          </label>
        ))}
      </div>
      ...
    </CardContent>
  )
}

Answer №2

It is indeed possible to do this. Let's delve into it further:

function retrieveSavedCards(): string[] {
  const result: string[] = [];

  fetch("/retrieveSavedCards")
    .catch((error: Error) => {
        throw new Error(error.message);
    })
    .then((response) => {
        return response.json();
    })
    .then((cards: string[]) => {
        result.length = 0;
        cards.forEach((item, i) => {
          result[i] = item;
        });
    });

  return result;
}

You have the option to immediately return the incomplete result array and then await the promise resolution before populating result asynchronously. But does this approach align with your intended solution?

We would appreciate it if you could provide more context on the specific issue you are facing.

Answer №3

Recently, I encountered a similar problem and came up with this solution to address it:

export type UnpackPromise<T> = T extends {
    then(onfulfilled?: (value: infer U) => unknown): unknown;
} ? U : never;

This approach combines elements of generics, conditional types, and infer.

In your specific scenario, I recommend using the ReturnType Utility for the function and applying the UnpackPromise type to the result.

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

Incorporating Google Pay functionality within Angular applications

I have been attempting to incorporate Google Pay into my Angular project, but I am struggling to find reliable resources. My main issue revolves around the following code... <script async src="https://pay.google.com/gp/p/js/pay.js" onloa ...

Guide to sorting through an array for a particular keyword

In my array, I have objects with IDs and names. For example: { [ { "id": 1, "name": "this is book", }, { "id": 2, "name": "this is a test book", }, { "id": 3, "name": "this is a desk", } ] } Now, let's say I want ...

When conducting tests in Nest.js, it appears that the dependencies of ReportingService, specifically MasterMLRepository, cannot be resolved. This issue is likely due to Sequelize not being available in

As I work on writing tests in Nest.js, I encountered an error that has been quite challenging to resolve. Despite trying various solutions found online, such as adding Sequelize to different sections like imports, exports, etc., none of them seemed to work ...

React with TypeScript presents an unusual "Unexpected token parsing error"

Recently, I encountered an issue with my helper function that was originally written in JavaScript and was functioning perfectly. However, as soon as I introduced TypeScript into the mix, strange behaviors started to surface. Here is the snippet of code fr ...

What is the best way to assign a type based on a variadic type in TypeScript?

TypeScript playground link For my current project, I am designing a custom route handler creator for Express. The goal is to allow passing arbitrary assertions as initial arguments before invoking the route handler callback. Here's an example of how ...

Ensuring a precise data type in a class or object using TypeScript

I am familiar with Record and Pick, but I struggle to grasp their proper usage. My goal is to ensure that a class or object contains specific data types such as strings, Booleans, arrays, etc., while also requiring properties or fields of Function type. in ...

Struggling to retrieve dataset from Bootstrap 5 form while using Angular

With the combination of Angular and Bootstrap 5, I have crafted this unique HTML form: <div class="mb-3"> <label for="genreName"> Type name</label> <div *ngIf="!enterTheGenre" class="form-group&qu ...

Querying data from a promise and embedding it in a JSON object in AngularJS

Attempting to retrieve data from a promise within a JSON object for the first time has presented me with a challenging task. The typical approach looks something like this: Service JS app.factory("dataService", ["$http", function ($http) { fu ...

Is it Observable or Not? Typescript Typehint helping you determine

I'm facing an issue while writing a function with correct typehints. It seems to work fine with explicit type hinting but breaks down when trying to use automatic type hinting. Can someone please help me identify the error in my code and suggest how I ...

Error: Could not find module: Unable to locate 'rxjs/add/observable/throw' in 'D:AngularhttpErrorHandlingExamplesrcapp'

I'm working on an Angular project to practice error handling, but I encountered an issue when trying to import the 'throw' module. The error message reads as follows: Error Message: "ERROR in ./src/app/employee.service.ts Module not found: E ...

Navigation arrows for sliding`

Is there a way to add custom right/left arrows to the Ionic slider component? Demo: Check it out on Stackblitz Note: Make sure to refer to the home.html page for more details. https://i.sstatic.net/jQ62l.png .html <ion-slides [pager]="true" [slide ...

When using PrimeNG's InputOtp component, users are unable to modify the values of input fields

When using the p-inputOtp component from PrimeNG for OTP input, I've observed that changes can be made until three out of four boxes are filled. Once all four boxes are filled, modifying the input is no longer possible. Is there a way to enable change ...

Automatically compile files while performing an npm install or update

I am looking for a way to automatically compile my TypeScript code into JavaScript when another project requires it. For example, when a project runs npm install or updates with my project as a dependency, I want a specific command to be executed after all ...

It appears that using JQuery's .when and .done functions may result in the code executing before the script has finished loading

Since updating the hard-coded <script> with JQuery promises, I have been encountering these errors frequently: https://i.stack.imgur.com/xkWAk.png The issue seems to be inconsistent in replicating. Sometimes, the error occurs while loading the page ...

Explain a category of instance used in a template parameter

I am currently working on implementing a basic IOC container with type-checking capabilities. My goal is to pass the "register" method an abstract class type along with an instance of a derived type. In the "resolve" function, I aim to provide an abstrac ...

Use the Express application as an argument for the http.createServer function

Encountering an error when trying to use express.Application as an argument for http.createServer: error TS2345: Argument of type 'Application' is not assignable to parameter of type '(request: IncomingMessage, response: ServerResponse) =&g ...

Form a tree structure using a compressed object

I’m struggling with a specific issue: I have an object structured like this: Object { id: string; parentId: string; } What I’m aiming for is a nested object structure like this: NestedObject { id: string; parentId: string; children: [ { ...

Found a minor syntax problem in an Angular service related to error handling declaration

As I was working on customizing the Angular tutorial to fit my needs, I found myself wanting to merge the two error handler methods showcased in the tutorial into one. I appreciate the functionality of both methods and believe combining them will be benefi ...

What advantages could learning ReactJS first give me before diving into NextJS?

Just mastered TS and now faced with the decision of choosing a framework. I'm curious why it's recommended to learn ReactJS before NextJS. I've read countless articles advising this, but no one seems to delve into the reasons behind it. Ca ...

Create an Angular 2 webpack production project and ensure that the dist folder does not contain any source code

I am currently developing a web application using Angular 2 with TypeScript and angular-cli. I needed to test the application on the server without uploading the source code, so I used the command "ng build --prod". Despite deleting all .map files from the ...