What's the best way to maintain the return type of a function as Promise<MyObject[]> when using forEach method?

I am currently working with a function called search, which at the moment is set up to return a type of Promise<MyObject[]>:

export function search(args: SearchInput) {
        return SomeInterface.performSearch(args)
            .then(xmlRequest => AnotherInterface.post(xmlRequest))
            .then(xmlResponse => SomeInterface.performSearchResponse(xmlResponse)) // performSearchResponse returns Promise<MyObject[]>
            .then(searchResponse => searchResponse.forEach(convertIDs)); // returns Promise<void>
    }

function convertIDs(obj: MyObject) {
    if (obj.id === 'foo') {
        obj.id = 'bar';
    }
    return obj;
}

I am facing an issue where I want to add a new line at the end that applies the convertIDs function to the results of the original function. However, this adjustment causes the function to no longer return Promise<MyObject[]> but instead Promise<void>. Unfortunately, this change breaks other parts of the code that depend on the function returning Promise<MyObject[]>.

Is there a solution or workaround that would allow me to apply the convertIDs function to the results while still preserving the original return type?

Answer №1

Utilize the Comma Operator to retrieve the initial value

 .then(searchResponse =>
          ( searchResponse.forEach(convertIDs) , searchResponse )
       ); // will return the same Promise<MyObject[]> it received

(the comma operator disregards all values except the last one, which is then returned)


This can also be written as

 .then(searchResponse => {
    searchResponse.forEach(convertIDs) 
    return searchResponse 
  })

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

Using React with Typescript and ie18next to fetch translations from an external API

In the past, I have experience working with i18next to load translations from static json files. However, for my current project, I need to load all translations from an API. How can I achieve this? Additionally, how can I implement changing the translat ...

Tips for sending a parameter within a JavaScript confirm method?

I currently have the following code snippet in my file: <?php foreach($clients as $client): ?> <tr class="tableContent"> <td onclick="location.href='<?php echo site_url('clients/edit/'.$client->id ) ?>&ap ...

The Implementation of Comet Programming

I'm interested in creating a web application similar to Google Docs where multiple users can edit and view changes in real-time. Would Comet Programming be the best approach for this? As a newcomer to Web Development, I'm currently learning Java ...

Comparing Two Items between Two Arrays

I have a scenario where I need to compare values in two arrays by running a condition. The data is pulled from a spreadsheet, and if the condition is met, I want to copy the respective data. For instance, I aim to compare two cells within a spreadsheet - ...

Is it considered safe to display the error message from an AJAX call for security reasons?

When I make my ajax calls, they usually follow this pattern: $.ajax({ type: 'POST', url: '/Controller/DoSomethingSpecial', contentType: 'application/json;', ...

Create an array of various tags using the ngRepeat directive to iterate through a loop

I'm familiar with both ngRepeat and forEach, but what I really need is a combination of the two. Let me explain: In my $scope, I have a list of columns. I can display them using: <th ng-repeat="col in columns">{{ col.label }}</th> This ...

Trigger a function post-rendering in a React component

Hey everyone, hope you're having a great day! I've been diving into React for a few months now. I'm making an effort to steer clear of using the traditional React Components, opting instead for React Hooks. However, there are instances wher ...

How can I showcase array elements using checkboxes in an Ionic framework?

Having a simple issue where I am fetching data from firebase into an array list and need to display it with checkboxes. Can you assist me in this? The 'tasks' array fetched from firebase is available, just looking to show it within checkboxes. Th ...

Transforming nested JSON files into nested jQuery divs

Is it possible to iterate through two JSON files that have a parent-child relationship based on simple ID primary and foreign keys? Can we then display the data in a list of divs with the following characteristics: Hierarchical - child divs should only a ...

I require displaying the initial three letters of the term "basketball" and then adding dots

Just starting out with CSS and struggling with the flex property. Seems to work fine at larger sizes, but when I reduce the screen size to 320px, I run into issues... Can anyone help me display only the first three letters of "basketball ...

Fix a typing issue with TypeScript on a coding assistant

I'm struggling with typing a helper function. I need to replace null values in an object with empty strings while preserving the key-value relationships in typescript // from { name: string | undefined url: string | null | undefined icon: ...

Sending PHP output data to jQuery

Trying to implement this code snippet /* Popup for notifications */ $(document).ready(function() { var $dialog = $('<div></div>') .html('message to be displayed') .dialog({ ...

Incorporating SEO for a Flash-Based Website

After reading through various discussions on this topic, it seems like my question still remains unanswered. We are gearing up to revamp our company's website in the coming months. Currently, our site is mostly text-based, which has helped us achieve ...

Present pop-up messages in the most sophisticated manner

I have successfully created an AngularJS app that is functioning well. Now, I am faced with the challenge of displaying different pop-ups based on specific conditions being met. I am unsure of the best approach to take. Currently, I am considering two op ...

What steps can I take to ensure that the original field does not regain focus once the dialog is closed?

My users prefer not to switch from the keyboard to mouse while filling out an input form. To address this, I am using the onFocus event to display a JQuery UI Dialog. However, when I use the dialog's close(); function, the dialog reopens as the origin ...

Is there a way to focus on a specific iteration of the ngFor loop in Angular 9 using jQuery?

I'm working on a list of items inside a modal that uses *ngFor with checkboxes. The goal is to cross out the contents of an item when its checkbox is clicked. Here's the initial code using jQuery in home.component.ts: $('body').on(&apo ...

Updating the iFrame source using jQuery depending on the selection from a dropdown menu

I want to create a dynamic photosphere display within a div, where the source is determined by a selection from a drop-down menu. The select menu will provide options for different rooms that the user can view, and the div will contain an iframe to showca ...

Error: JavaScript alert box malfunctioning

I am facing an issue with my JavaScript code. I have successfully implemented all the functionalities and can change the color of an image background. However, I am struggling to prompt a pop-up message when clicking on an image using "onclick". I have tri ...

Show the JSON data that was returned

I'm encountering a problem trying to access and display the returned object. Since it's cross-domain, I'm using jsonp, but I'm unable to retrieve the returned object for some reason. $(function(){ var API = "https://ratesjson.fxcm. ...

The issue of conflicting checkboxes and types plugins in jstree

Working on constructing a tree with the jstree JavaScript library and incorporating two jstree plugins: checkbox plugin types plugin Below is a snippet of code for reference: var mydata=[ id: "1", parent: "#", text: "node1", }, { id: "2", parent: " ...