Inconsistency in product returns following promise mapping - Utilizing Ionic, Angular, and Typescript

When I retrieve items from a database for a feed, it is crucial that they remain in the same order as retrieved. However, despite mapping the array from the query, the displayed feed objects end up out of sequence. Here's the snippet of code:

    let cacheKey = 'promos';
    let promises_array:Array<any> = [];
    let mapped;
    this.cache.removeItem(cacheKey);

    this.cache.getItem(cacheKey).catch(() => {
      let store = [];

      this.list2 = this.af.list('/promos', {
      query: {
        limitToLast: 10
      }});

      this.subscription4 = this.list2.subscribe(items => {
        mapped = items.map((item) => {
          return new Promise((resolve,reject) => {
            let storageRef = firebase.storage().ref().child('/settings/' + item.customMetadata.username + '/profilepicture.png');

            storageRef.getDownloadURL().then(url => {
              console.log(url + "in download url !!!!!!!!!!!!!!!!!!!!!!!!");
              item.customMetadata.picURL = url;
              store.push(item.customMetadata);
              resolve();
            }).catch((e) => {
              console.log("in caught url !!!!!!!$$$$$$$!!");
              item.customMetadata.picURL = 'assets/blankprof.png';
              store.push(item.customMetadata);
              resolve();
            });


          })
        })

        console.log(JSON.stringify(mapped) + "    mappped things");



        this.startAtKey = items[0].$key;
        this.lastKey = this.startAtKey;

        let results = Promise.all(mapped);
        results.then(() => {
        //setTimeout(() => {

          this.items = store.reverse();
          //this.classesListArray.reverse();   
          console.log(JSON.stringify(this.items) + " value value vlaue items");
          return this.cache.saveItem(cacheKey, this.items);
        //}, 3000);

        })
      })
    }).then(data => {
      this.items = data;
    })

I suspect that the images load at varying speeds each time, causing them to be arranged out of order during mapping due to their loading times. Another concern is whether the returned data from the request is an actual array. When checking typeof items within the subscription, it shows as object, yet JSON.stringify displays an array structure - could this discrepancy be responsible for the loss of order? Is it possible that it's not really an array?

Answer №1

Make sure to arrange the items only once you have collected them all.

arrangeItems.sort((x,y) => {
    return x.property - y.property;
});

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

Is there a way for me to access the names of the controls in my form directly from the .html file?

I have a list where I am storing the names of my form controls. In order to validate these form controls, I need to combine their names with my code in the HTML file. How can I achieve this? Below is my code: .ts file this.form = this.formBuilder.group({ ...

Verify in Typescript if there is at least one value supplied

Looking for a solution: function takeOneOfOrThrow(firstOptionalVariable : string | undefined, secondOptionalVariable : string | undefined) { let result : string; if (!firstOptionalVariable && !secondOptionalVariable) { throw new E ...

Angular HTTP client fails to communicate with Spring controller

Encountered a peculiar issue in my Angular application where the HttpClient fails to communicate effectively with the Spring Controller. Despite configuring proper endpoints and methods in the Spring Controller, the Angular service using HttpClient doesn&a ...

What is the best practice for Angular: running production build before or after testing?

When developing a Java application for production, I typically set up the build process to create the production artifacts first and then run tests against those artifacts. Recently, I joined an Angular project and noticed that the build process is struct ...

Having difficulty accessing custom cells in Angular ng2-smart-table for search functionality

When rendering a "custom" field, one issue that arises is that the global search feature is no longer effective within it. This could be due to the fact that the cell initially appears as a JSON object and then only a single string is rendered from that ...

Different Types of Props for Custom Input Components using React Hook Form

Struggling with creating a custom FormInput component using React Hook Form and defining types for it. When calling my component, I want to maintain autocompletion on the name property like this ... <FormInput control={control} name={"name"}& ...

In my main method, I am attempting to define and set up a two-dimensional array

public static void main(String[] args) { // Implement logic here int[][] twoDArray = new int [2][4]; for (int i=0; i<twoDArray.length;i++){ twoDArray[i]= new int [i+1]; System.out.println(Arrays.toString(twoDArray[i])); ...

Challenges encountered when testing middleware in a TypeScript Node.js Express project

I have been exploring the repository at https://github.com/goldbergyoni/nodebestpractices to enhance my understanding of nodejs best practices. Below is a middleware I developed: import { NextFunction, Request, Response } from "express"; import ...

Swagger Issue Resolved: Restriction on Number of Params Set

After setting up this option for my route, I noticed that when accessing the first parameter (page), it correctly returns the value entered in Swagger UI. However, when trying to access the second parameter (genre), it seems to interpret it as a string &ap ...

Sending a signed char array to a function that requires a const char pointer will lead to scrambled values in the array

I'm struggling to understand the process happening here: There is a function in my code that calculates the difference between two dates in seconds. This calculation is then manipulated through bitwise shifting to generate an output: void CalculateT ...

The observable HTTP map appears to be more of a representation rather than a concrete entity

I seem to be struggling with understanding Typescript I expected the returned observable to have a method getTitle(), but it seems to be missing. Instead, I am getting an object that resembles AttachableContentModel without that particular method. What is ...

Array input for CodeIgniter

I'm currently working on a dynamic form where clicking the add button adds a new line to the form. However, when I try to echo the output, it's not displaying as expected. Here is my code: public function inputData(){ $provinsi = $this-& ...

An issue has occurred: Unable to access the 'seatsavailable' property of an undefined object

Currently, I am immersed in a project involving Angular 6 and utilizing the @Input and @Output decorators. In this scenario, I have the Bookride Component functioning as the parent component with RideDetails serving as the child component. Successfully tra ...

Getting the local path of a file from an input file in Angular 7

Is there a way to retrieve the local file path from an input field in HTML? After running the code below, I obtained 'C:\fakepath\fileTest.txt' I am looking for a method to get the local path so that I can pass it on to my control ...

Typescript React: Implementing type definitions for JSS classes object

Here is the react code I am working with: import React from 'react'; import withStyles from "react-jss"; const styles = { box: { border: "2px solid #000" } }; interface ComponentProps {} class Welcom ...

The type 'Observable<Subscription>' does not match the type 'Observable<MyData>' in RxJS Angular

When utilizing Angular, I've developed a service that retrieves data from multiple sources and combines it with the original service. Below is the code snippet: searchData(): Observable<MyData> { const url = `${this.context}/search`; ret ...

What is the proper way to combine two arrays containing objects together?

I am faced with the challenge of merging arrays and objects. Here is an example array I am working with: [ { name: "test", sub: { name: "asdf", sub: {} } }, { name: "models", sub: {} } ] ...

Using Typescript to extract the type from within the function type parameters

I am currently utilizing an imported type definition that contains a function type definition with a fairly complex parameter type: export interface SomeTypeDefinition { someFunction: ( param1: string, param2: { key1: number, key2: s ...

The output is displaying an Object instead of a numerical value in JSON

When I try running the URL in Chrome, the output I receive is: { "Train_score": { "0": 0.9892473118 }, "Test_score": { "0": 0.9831932773 } } However, when I attempt to use the following code to retrieve the JSON data using Javascript, co ...

Update a value in the sessionStorage using Angular

I am working on a function that handles checkbox options based on event.target.name. The goal is to add the checkbox option to session storage if it's not already there, and update the value if it exists. However, I'm facing some issues with my c ...