invoking an API within a map function and utilizing the response

vm.owners = parents.children.map(function(e) {
  getparentById(e.Id)
    .then(function(getresponse) {
      var parentLink = '<a href="/#/parent/onboard/' + e.Id + '"  target="_blank">' + e.Number + "-" + e.Name + "-" + getresponse.code + '</a>';
      return parentLink;
    })
    .finally(function() {
      vm.isLoading = false;
    });
  
}).join('  ||  ');

The code above is attempting to concatenate the values of a looped function with '||' as it iterates through children and makes an API call using getparentbyid. The issue arises when trying to combine the results into a single string due to where the HTML concatenation takes place. Moving it outside the getparentbyid API call works for combining with '||', but the data from getresponse is then inaccessible. Placing it inside the getparentbyid function results in empty spaces being joined by '||'. The challenge here is finding a way to successfully join both pieces of data together. Any suggestions on how to address this dilemma?

Answer №1

Your function parameter for .map() must return a value; it's currently not doing so. Add a return statement before the getparentById() call to ensure it returns the Promise created.

After this adjustment, the map() call will produce an array of Promises that should resolve. You can utilize Promise.all() to handle this, returning a single Promise. Subsequently, use .then() on this Promise to manipulate the resulting text array.

vm.owners is only assign-able within this .then() callback due to result availability post completion of all getParentById() calls.

The code setting vm.isLoading = false after assembling each individual link may need adjustment. Consider incorporating finally() directly following the final .then() for proper positioning.

The revised block may resemble:

Promise.all(parents.children.map(function(e) {
  return getparentById(e.Id)
    .then(function(getresponse) {
      var html = '<a href="/#/parent/onboard/' + e.Id + '"  target="_blank">' + e.Number + "-" + e.Name + "-" + getresponse.code + '</a>';
      return html;
    })
}))
.then(function(result) {
  vm.owners = result.join('  ||  ');
})
.finally(function() {
  vm.isLoading = false;
});

To enhance readability, you may opt to employ async/await in restructuring the code. This alternative approach would appear as follows:

const listOfPromises = Promise.all(parents.children.map(async function(e) {
  const getresponse = await getparentById(e.Id)
  return  '<a href="/#/parent/onboard/' + e.Id + '"  target="_blank">' + e.Number + "-" + e.Name + "-" + getresponse.code + '</a>';
}))
const allResults = await listOfPromises
vm.owners = allResults.join('  ||  ')
vm.isLoading = false

To implement this pattern, your code either needs to be enclosed within an async function or incorporate top level await functionality.

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

Setting an attribute on a custom component that is dynamically created within an Angular application

I am working with a custom library component called <my-icon>. To display the icon, I need to specify the property [name] like this: <my-icon [name]='warning'></my-icon> Currently, I am dynamically creating these icons in Type ...

When using Expressjs MVC, encountering difficulties in retrieving data from mongoose in the listAll() function within the router

I'm currently working on implementing MVC-like architecture in Express.js for a very specific scenario. I suspect there may be an issue with promises, but I'm struggling to debug the problem effectively. Here's how the architecture is set u ...

When the enter key is pressed in a contenteditable div, line breaks are disregarded

Is there a way to ensure that when the return key is pressed to start a new line for a post, the output actually starts on a new line? I've been having trouble with this and would like to know the most common solution. Check out the demo below for te ...

Is it possible to define a state within a map function?

This section of my code retrieves JSON data from the backend API and displays it as a list. Here is an example of my JSON data: (15) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}] 0: {id: 1, t ...

Learn how to incorporate the dynamic array index value into an Angular HTML page

Exploring Angular and facing a challenge with adding dynamic array index values in an HTML page. Despite trying different solutions, the answer remains elusive, as no errors are being thrown. In TypeScript, I've initialized an array named `months` wh ...

Incorporating a JavaScript script into my Angular 7 project

My project requires me to incorporate the "Loadingbar.js" library into one of my pages. You can find this library here: . Initially, I inserted the CSS code into my global "style.css" file. I started by placing the script in my index.html file: <script ...

Execute the JavaScript [ window:print() ] function once the webpage has finished loading along with any

I am facing an issue with my web page that has around 10 Google Analytics charts. I want to trigger a print dialog box once the page is fully loaded, including all the charts and JavaScript. Currently, the problem is that the print dialog box opens after t ...

Executing a POST Request using a Custom Node Module in Express

I'm in the process of developing a web application where the user inputs their username, submits it, and then the application processes the input through a POST request to another server. Based on the response from the external server, the user is red ...

MongoDB: Issue updating the 'role' field of a document

Recently, I've run into an issue where I am unable to update the 'role' of a specific document. The document in question is a 'user' object within the MEANjs User schema, and it has a pre-defined property for roles. Here is the sec ...

What methods should I employ to effectively test a custom icon function?

I've written a function that creates a Leaflet icon with specified properties: createIcon( url, retinaUrl: string = null, height: number = 20, width: number = 20 ): Icon { const icon: Icon = L.icon({ iconUrl: url, ico ...

What are some ways to streamline inline styling without having to create numerous variables?

Currently, I am in the process of constructing a tab component and establishing inline variables for CSS styling. This particular project involves a streamlit app that allows me to modify settings on the Python side. At the moment, there are four elements ...

Is it appropriate to refer to a single page application as a web 3.0 application?

As time progresses, we are witnessing the rise of more and more single page applications or frameworks such as new twitter and Sammy. It appears to be a significant advancement where we move away from generating code on the server side, with servers actin ...

Enhance the visual appeal of Autodesk Forge Viewer by incorporating environmental textures

Is there a way to incorporate an environmental texture into Autodesk Forge Viewer v6.0? I know in Three.js you can apply a texture to the scene's background and environment, so how would I achieve this in APS viewer? I'm not looking for a skybox ...

Convert Excel Spreadsheet data into an interactive HTML chart in real time

Looking for a solution to update an Excel spreadsheet monthly and display it on a Blackberry browser? I've already built a website with all the spreadsheet information using HTML lists and CSS for charts. I need help loading a new spreadsheet into th ...

Preventing autoscrolling in Ionic's dual side menu template when additional content is added

Could anyone kindly assist me in figuring out why the autoscrolling of the content is not functioning correctly? Whenever the button on the header is clicked, a new message will be included in the main content. However, once the number of lines exceeds wha ...

I'm curious if there is a method to indicate the specific destination within a separate file that the FS module in Node.js writes the data

Whenever I utilize the fs method fs.appendFileSync(example.json, jsonString, {'flags': 'a+'});, it successfully writes the data to the JSON file. However, the problem is that the data is not inserted into the array where I actually need ...

What are the best methods for preserving paint color when changing wheel styles, and vice versa?

I posted this query about a year ago, but I did not have a fiddle prepared at that time and my question was not as well articulated as it could have been. Despite that, many people came forward to offer their help, and I am truly grateful for that. This ti ...

Unable to update div CSS using button click functionality

I have been working on this HTML/CSS code and I am trying to change the style of a div using a JavaScript button click event so that the div becomes visible and clickable. However, despite my efforts, it doesn't seem to be working as expected. Whenev ...

Apologies, but it seems there was an issue reading the "checked" property as it is null

I am currently facing an issue with the submit button in my Django application. It appears that the Javascript function is unable to determine which checkboxes are checked, as all I see in the console logs are "cannot read properties of null, reading "chec ...

Running multiple web applications with different base directories on a single Express server

I am currently working on serving a website that requires different static directories for various routes. When a GET request is sent to the /tools* route, I want to utilize the /dist/toolsApp/ directory as the base directory for my frontend code. If ...