Guide to extracting the value from a promise response and assigning it to every object property within an array in Ionic version 3

tried attempt 1: I made an effort to extract data using the function below. Due to its asynchronous nature, I encountered difficulty in retrieving the value from this function.

for (var i = 0; i < this.items.length; i++) {
    let newitems: any = this.items;
    this.restapi.getPendingOrdersCount(this.items[i].store._id, this.user._id).then(data => {
        this.result = data;
        console.log(this.result);
        //able to get the data here
    });

    //Unable to fetch the data here.
    newitems[i].pendingCount = this.result;
    console.log("result", this.result);
}

attempt 2: I introduced an additional variable to the previous function and added a return statement. Now I am able to access this data but it appears as a zone value instead of the actual value => t {__zone_symbol__state: null, __zone_symbol__value: Array(0)}

let newitems: any = this.items;
for (var i = 0; i < this.items.length; i++) {
    var response = this.restService.getPendingOrdersCount(this.items[i].store._id, this.user._id).then(data => {
        this.result = data;
        //console.log(this.result);
        return response;
    });
    //able to access result here but it shows as a zone value
    newitems[i].pendingCount = this.result;
    console.log("response", response);
}

Seeking assistance in rectifying the above function for reusability of promise value.

Answer №1

If the function getPendingOrdersCount returns a Promise, you can easily implement the async/await approach. Here is an example:

const result = await this.restapi.getPendingOrdersCount(this.items[i].store._id, this.user._id);
console.log(result); // will display the values received

Remember that you can only use await within an async function. Therefore, if you are calling getPendingOrdersCount inside a method like ngOnInit(){}, you need to modify it to async ngOnInit(){}.

For further information on async/await, please visit this link.

Answer №2

Utilizing an async call to getPendingOrdersCount, make sure to execute the

console.log("response",response);
before .then to ensure that data is not lost outside of .then.

To access the data outside of .then, you can invoke the dislayResult function as demonstrated below.

this.restapi.getPendingOrdersCount(this.items[i].store._id, this.user._id).then(data => {
  this.result = data;
  console.log(this.result);
  //able to get the data here
  
  displayResult();
});

displayResult() {
   console.log(this.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

Scrolling horizontally using jQuery and CSS

I have been experimenting with creating a horizontal scrolling page that moves to the right when scrolling down and to the left when scrolling up. Here is the current code: HTML <div class="scroll-sections"> <section id=&quo ...

The Power of Ajax in PDF Retrieval

At my workplace, we have an innovative approach to ajax using a custom in-house framework. Essentially, within a JavaScript function, I use the following code: CT.postSynch('report/index/downloadProjectsInProgress', {}, function(data){ } ...

Exploring ways to extract an element from a newly opened window and set a value using JavaScript

I have been successfully using web_browser.document.getElementById() for the login screen, but I am encountering an issue when trying to use it after logging in and opening a new window. Can someone please assist me with this problem? Below is the code t ...

What is the process for obtaining an HTML form, running it through a Python script, and then showcasing it on the screen

I am inquiring about the functionality of html and py script. .... The user enters 3 values for trapezoidal data from the html form: height, length of side 1, and length of side 2, then clicks submit. The entered values are then sent to be calculated using ...

The cross-origin resource sharing configuration has not been implemented

I have SenseNet 7.0.0 and ASP.NET 5.2.3 set up, with my Angular (Typescript) application running on localhost:4200 and the ASP.NET application running on localhost:55064. I followed this tutorial for installing Sensenet and used this tutorial for installin ...

Creating the visual blueprint of components in Angular 6

Recently embarking on the development of an Angular 6 application, I find myself already with a plethora of components at hand. Considering the need for thorough documentation, I ponder the existence of a reliable tool capable of generating a visual repre ...

Best practices for organizing an array of objects in JavaScript

I have an array of objects with nested arrays inside, and I need to restructure it according to my API requirements. [{ containerId: 'c12', containerNumber: '4321dkjkfdj', goods: [{ w ...

Binding textarea data in Angular is a powerful feature that allows

I am looking to display the content from a textarea on the page in real time, but I am struggling to get the line breaks to show up. Here is my current code snippet: app.component.html <div class="ui center aligned grid">{{Form.value.address}}< ...

Size of subarray in a multidimensional array

Currently, I am working with an object where I am inserting integers, strings, and arrays into one main array. My goal is to determine the length of a specific array that is located within this main array. Below is the code I am using: var all_categories ...

Acquiring the input from a text box to generate a hyperlink on the current page

I am trying to generate a link that has the href attribute as follows: app\process?val=12000 The catch is that the value for the val parameter (in this case 12000) needs to be derived from a textbox on the page. I am aware that I can retrieve the ...

Update the scatter/line chart dynamically in Chart.JS by incorporating multiple x and y grids for enhanced visualization

I need to develop a new function that will allow me to input data to update my line chart. Here is the current state of my function: function updateChart(label, xp1, yp1, xp2, yp2) { chart.data.labels.push(label); chart.data.datasets.data.push({x: xp1 ...

Ensuring User Information Persistence in React Upon Successful Login

I am developing a small application using React with PHP as the back-end. Within my database, I have two types of users - admin and student. Upon user login, I store their information in session storage like this ( user: { username:'abcxyz123', r ...

Displaying overlay when sidebar menu is expanded

I am working on creating a smooth overlay transition for when the sidebar menu opens and closes. When the overlay is clicked, I want the menu to close. This is what I have so far: $(document).ready(function() { $('#menu-toggle').click(fun ...

The Angular state provider seems to be having trouble when adding the .html extension to the URL parameter

I am currently implementing ui-router version 1.0.0-beta.1 and my state configuration appears as follows: .state('start.step2', { url: '/step2', template: startStep2, reloadOnSearch: false, ...

Stop Scrolling in VueJS

I am currently facing a challenge in preventing scrolling only when the lightbox component is open. I prefer not to rely on any external libraries or plugins for this task. Within my App.vue file, I have included the "LightBox" component. Therefore, it se ...

Why isn't $.post functioning properly in any instance?

I've been experiencing issues with my $.post calls throughout my code. Despite not sending requests to different domains, everything is localhosted. My Mac OS X 10.8 automatically defined my localhost alias as ramon.local, and I'm trying to make ...

Tips for implementing async/await with the file system module

Can you explain the approach to deleting a file using the async/await syntax in combination with fs.unlink() for a specified path? ...

The "a" HTML link element is stubbornly resisting being attached to an event listener

I have implemented the MutationObserver observer in my program to monitor the addition of elements. One specific condition I am checking for is if the added element is an anchor tag (tag="a") and if the link is a DOI, then I attach a contextmenu ...

The caching of Document.write is impacting the website's performance

I have a script that uses document.write before the page loads to inject html into my page. However, this content gets heavily cached and only updates with a hard refresh. I know I shouldn't be using document.write, but for now, I need a quick soluti ...

Ways to dynamically update activeIds in ngb Accordion based on the clicked button in Angular

I need assistance with implementing the ngbAccordion within a modal in another component. My goal is to have the modal open with the "Acc1" tab displayed when button 1 is clicked, and similarly for button 2. If anyone could provide guidance, I would great ...