What is the process for determining the array length from a promise?

I am looking for a way to calculate the length of an array returned by a promising function:

getUserStockMovementList(userID: string): Promise<calculatedMovement[]>

Any suggestions on how to achieve this?

Is it possible to store a promise-returning function in a constant variable?

const  stockMovements = getUserStockMovementList(userID);
for (let i = 0; i < rawMovementList.length; i++) {
// perform actions
}

Answer №1

When you call this async method, you will receive a Promise of the array instead of the actual Array instance. To access the actual array instance, it is necessary to await the promise:

async someAsyncFunction () {
   const  rawMovementList = await rawMovementListOfTheUserForTheStockCode(userID, code);
   for (let i = 0; i < rawMovementList.length; i++) {
      // do stuff
   }
}

Alternatively, you can use the older approach with then:

rawMovementListOfTheUserForTheStockCode(userID, code).then(rawMovementList => {
    for (let i = 0; i < rawMovementList.length; i++) {
      // do stuff
   }
})

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

Importing the isPropertyUpdated method in Angular 4

My challenge lies in utilizing the isPropertyUpdated function within Angular 4. However, I have encountered a roadblock as Angular 4 does not facilitate deep imports. An example of an import that fails to work on Angular 4 is: import {isPropertyUpdated} ...

Is there a more efficient method for generating dynamic variable names from an array aside from using eval or document?

I need help figuring out how to create an array in JavaScript or TypeScript that contains a list of environment names. I want to iterate over this array and use the values as variable names within a closure. My initial attempt looks like this (even though ...

Utilizing Node modules in TypeScript, Angular 2, and SystemJS: A Comprehensive Guide

In the process of developing a simple Angular 2 application, I am constructing a class named User. This class includes a function called validPassword() which utilizes the bcrypt library to validate user passwords: import { compareSync, genSaltSync, hashS ...

The information retrieved from the API is not appearing as expected within the Angular 9 ABP framework

I am facing an issue with populating data in my select control, which is located in the header child component. The data comes from an API, but for some reason, it is not displaying correctly. https://i.stack.imgur.com/6JMzn.png. ngOnInit() { thi ...

The function is not defined for this.X in TypeScript

I am currently developing an application using Angular 6. Within my app, I have the following code snippet: import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: ...

What is the best way to perform a conditional check and return a customized object while working with a Promise?

I have developed a provider specifically for handling all Firebase database related requests. In the getUser method, when the data is fetched from the database using .once which returns a promise, if the object is null it currently returns null. This means ...

Send Components to another component without specific TypeScript typespecified

Struggling with a situation where I am faced with the challenge of working around strongly typed variables. The issue arises with a set of icons as components and an icon wrapper component. The wrapper component requires a themeMode variable to determine ...

Listening to changes in a URL using JQuery

Is there a way to detect when the browser URL has been modified? I am facing the following situation: On my webpage, I have an iframe that changes its content and updates the browser's URL through JavaScript when a user interacts with it. However, no ...

Experimenting with Jest in a VueJS2 application that utilizes Typescript

I'm currently working on a VueJS 2 project and I've been trying to integrate TypeScript into it. The challenge I'm facing is setting up Jest tests for my components. Here's a snippet of my TypeScript component: <template> < ...

Modifying the property value based on the selected item from a dropdown menu in Angular 2

I am brand new to Angular 2 and I have come across the following code snippet. <select name="shape_id" (change)="changeShape()"> <option *ngFor="let shape of shapes" [ngValue]="shape.name"> {{shape.name}} </option> </s ...

angular 2 loading elements synchronously

Within my local or session storage, there exists a JWT token containing the userId information. When a user refreshes the page on a route such as test.com/route2 the app.components.ts initiates an http request to fetch the roles. constructor( p ...

Run a Promise with RxJS, followed by a combination of the latest values

Apologies for bombarding you with more questions recently, but I'm really struggling to understand how everything links together. Currently, a user is utilizing promise-based storage to store the names of feeds they wish to filter out. The Social Fee ...

Encountering an undefined property error when trying to access 'userService' while implementing an async validator in Angular 12

For the past few days, I've been struggling to implement async validation with no success from various tutorials and solutions! Service code- getUserIdToCheckDuplicate(userId:any):Observable<any>{ const url = ``; //url goes here return ...

Having trouble with loading JavaScript during ng build --prod process

The JavaScript file I'm using for multiple emails (multiple_emails.js plugin) works well with ng serve. Here is my code: (function( $ ){ $.fn.multiple_emails = function(options) { // Default options var defaults = { ...

Is there a way to determine if an array includes an integer value?

I've been attempting to iterate through an array to verify if it includes an integer, but I'm struggling to make it work and I'm not sure why. Is it necessary to use the map method? Here is my code snippet: let words = ['Dog', & ...

Creating input fields in Angular 2

Can someone guide me on how to sum the values entered in two input fields? Here is my HTML code snippet. I'm not sure if there's anything missing in the ts file. <div class="small-7 columns"> <md-input-container> <input t ...

Error message encountered: Typescript, Webpack, angular - Unable to execute due to TypeError: Object(…) does not operate as

Just starting out with TypeScript and Angular, I've been tasked with creating a typedefinition for a custom library. Despite confirming that the JavaScript from my external library is loading correctly in the resources, I encountered an error when cal ...

Angular 10 does not fulfill promises as expected

In the Angular 10 project I'm working on, I encountered an issue while trying to call an API request asynchronously using promises. The code I wrote didn't seem to execute the API call as expected and kept exiting at the first line without progre ...

Sorting Two Sorted Arrays in Place to Allocate the First n Elements in the Initial Array and the Remaining Elements in the Other Array

Instructions for the task: You have been given two arrays of integers, both sorted in ascending order. Your goal is to separate the n smallest elements from the first array and store them in a new array, while storing the remaining elements in another arra ...

Using ES6, one can filter an array of objects based on another array of values

Seeking assistance with creating a function to filter an array of objects using another array as reference values. For example: The array containing objects: const persons = [ { personId: 1, name: 'Patrick', lastName: 'Smit ...