Patience is key as you wait for the map function to complete in TypeScript

I am facing an issue with the for each loop not waiting for the map function to finish, resulting in undefined ids. How can I ensure that all the ids are properly mapped?

getIndexes(){
 this.http.get<{data: {id: number, caption:string}[], paging: any, next: string}>(this.baseUrl +'me/media/?access_token=' + this.users + '&fields=id,caption&limit=9',
{responseType:"json"}).subscribe(response =>
  {
    const data = response.data.map(async l => {
      l.id
    })
    data.forEach(
    id => {
      this.http.get<{ media_url: string; id: string; }>(this.baseUrl + id + '/?access_token=' + this.users + '&fields=media_url').subscribe(res => {
        console.log(this.list);
        this.list.push(res.media_url);
        console.log(this.list);
        this.gallery.next(this.list);
      });
    }

  );
  }
)
}

Answer №1

Consider implementing the use of await in your code snippet

retrieveIndexes(){
 this.http.get<{data: {id: number, caption:string}[], paging: any, next: string}>(this.baseUrl +'me/media/?access_token=' + this.users + '&fields=id,caption&limit=9',
{responseType:"json"}).subscribe(async response =>
  {
    const data =await response.data.map(l => {
      l.id
    })
    data.forEach(
    id => {
      this.http.get<{ media_url: string; id: string; }>(this.baseUrl + id + '/?access_token=' + this.users + '&fields=media_url').subscribe(res => {
        console.log(this.list);
        this.list.push(res.media_url);
        console.log(this.list);
        this.gallery.next(this.list);
      });
    }

  );
  }
)
}

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

Unable to retrieve JSON data from php script, but able to successfully retrieve it from file.json

This is the function of my PHP testing script: $json = array ( "age" => 5, "name" => "Lee", ); $json = json_encode($json); echo $json; The JSON data is successfully printed out. When I save its content in a file named file.json and read ...

Having trouble with the clip-path in d3.js liquid fill gauge

Attempting to integrate the d3.js liquid fill gauge into my angular2 webapp has been a challenge. The clippath functionality seems to be malfunctioning, resulting in no wave being generated at all. https://i.stack.imgur.com/3Bmga.png instead of https://i. ...

The union type consisting of String, Boolean, and Number in type-graphql has encountered an error

I attempted to create a union type in type-graphql that represents the String, Number, and Boolean classes, but unfortunately, it was not successful. Does anyone have any suggestions on how to achieve this? export const NonObjectType = createUnionType({ ...

Using Angular 10 to make an HTTP POST request, with the goal of appending a string

Whenever I try to send a post request to an api endpoint, I keep encountering an error with status code 500. name: "HttpErrorResponse" ok: false status: 500 statusText: "Internal Server Error" Below is the code I am using: var selected ...

Steps for importing a CommonJS module with module.exports in Typescript

When working with ES5 code, I encountered an error that I cannot seem to resolve. Despite following the language spec and checking my TypeScript version 1.7.5, I still can't figure out why this error is occurring. Error TS2349: Cannot invoke an expre ...

Having trouble with adding multiple items to an SP list using sp/pnp as I keep encountering an error with the "createBatch()" method

I've been referring to the documentation at to guide me, but I'm encountering an issue with the following code snippet: import { SPFI, spfi, SPFx } from "@pnp/sp"; import "@pnp/sp/webs"; import "@pnp/sp/lists"; impo ...

Want to enhance user experience? Simply click on the chart in MUI X charts BarChart to retrieve data effortlessly!

I'm working with a data graph and looking for a way to retrieve the value of a specific column whenever I click on it, and then display that value on the console screen. Check out my Data Graph here I am using MUI X charts BarChart for this project. ...

Changing field visibility in Angular Reactive form (form validation) by toggling based on a checkbox in another component

I'm facing a challenge with a complex form where the fields depend on toggling checkboxes in a separate component (parent). My goal is to dynamically validate the form, with some fields being enabled and others disabled based on the toggling of the ch ...

What is the best way to create a calendar that displays every day in a single row?

Is it possible to create a calendar with all days in one row? I've been searching for a solution to this problem without any luck. It's surprising that I haven't found a clear answer or explanation on how to achieve this. I'm sure man ...

Error encountered when attempting to access an instance property or method using dynamic input within the square brackets in Typescript

Here is the code snippet that I am working with: class Label{ constructor( public name:string='name', public configPath:string='path', public foo:{bar:string} = {bar:'hello'} ){ } } const labelName:string = ...

An obstacle encountered when implementing feature module services in a controller for a Nest JS microservice

Recently, I developed a feature module named "user" which includes a controller, model, and services to interact with my postgres database. Despite setting up everything correctly, I encountered an error when trying to call userService from the feature mod ...

Tips on handling multiple Redux toolkit CreateApi interceptors

I came across this solution here for implementing a reAuth baseQuery in Redux Toolkit. I have several backend services that all use the same refresh token concept. Is there a way to create a single baseQueryAuth function that can be used by multiple creat ...

The argument supplied in Angular using TypeScript is incompatible: a 'string' type cannot be assigned to a parameter expecting an 'Element' type

I'm facing 3 errors with Typescript in angular when working with D3js elements. I tried to create a mouseover event to display tag and value data corresponding to the bar graph, but encountered issues. I attempted declaring strings and even added "noI ...

Compiling TypeScript files from multiple source directories

Having 3 NodeJs applications with the latest versions of Typescript code, each containing an "src" folder with TypeScript code files and a "dist" folder with JavaScript files compiled by Typescript. I am now looking to create a "common" folder outside of ...

Can we create a type-safe string-to-int map that is checked at compile-time?

Attempting to achieve a seemingly impossible task is not new to me. StackExchange has consistently surprised me, so I turn to you for assistance with the following challenge: I am in need of mapping names to integers. The list of names (around 2k) is uniq ...

Angular6 Observables used in API service with dynamic arguments

In order to achieve the desired behavior, I am trying to implement a system where when a user selects a label from a dropdown menu, an API call is made with that specific label as an argument. Subsequently, a chart should be redrawn using the data received ...

Assigning values to object properties in a TypeScript loop

I need to update a Feature object in my code. Here is a simplified version of the structure: type Feature = {id: number, name: string, deletedAt?: Date} const newData: Partial<Feature> & {id: number} = { id: 1, deletedAt: new Date() }; const ...

TypeScript fails to recognize that the filtered array consists entirely of one type when using a type guard

I recently stumbled upon this code snippet in a coding playground where TypeScript is used: export interface Page { heading: string; component: string; path: string; } export type RouteOnly = Pick<Page, 'heading' | 'path'> ...

Encountering "Unexpected token *" error when using Jest on an import statement

What could be the reason for Jest failing with the error message "Unexpected token *" when encountering a simple import statement? Error log: Admin@Admin-PC MINGW32 /d/project (master) $ npm run test > <a href="/cdn-cgi/l/email-protection" class="__ ...

The validation status of Angular's custom form array remains in a PENDING state when utilizing asynchronous validators

I've created a custom asynchronous postal code validator that can be used with Template Driven forms. @Directive({ selector: '[appAsyncPostalCode]', providers: [ { provide: NG_ASYNC_VALIDATORS, useExisting: AsyncPostalCodeValidatorDi ...