array size is not being accurately reported

As I try to make sense of this code, something seems off. It appears to be a straightforward portion of a promise chain.

let flightName = [];
let guidArr = [];

Promise.all(guidArr)
       .then(values => {
         for(var a = 0; a < values.length; a++) {
           Xrm.WebApi
              .online
              .retrieveRecord("crd80_flightplanevent", values[a], "?$select=_crd80_learnerflight_value")
              .then(
                function success(result) {
                  flightName.push(result["_crd80_learnerflight_value@OData.Community.Display.V1.FormattedValue"])
                },
                function(error) {
                  DisplayError(error)
                }); 
         }
         return flightName
       }).then(flightName => {
         console.log(flightName) 
         console.log(flightName.length)         
         return flightName
       })

https://i.sstatic.net/3so2V.jpg

The flightName array is correctly displayed in the console, but strangely, the length of flightName always shows as 0 despite the output showing a length of 2 when using console.log(flightName)

What could be causing this discrepancy? I am trying to access each item in the array but it doesn't seem to be working as expected

Answer №1

After receiving guidance from @derpircher, the solution provided was successful:

The issue stemmed from not awaiting the promises within the

for(var a = 0; a < values.length; a++)
loop. This resulted in an empty array when executing return flightName, causing console.log(flightName.length) to return 0. While console.log(flightName) may indicate that there are values present, it is actually referencing the object which is populated after promise resolution. By utilizing
console.log(JSON.stringify(flightName))
, the output reveals [] as the array remains empty at that point.

To address this issue, consider making the initial then handler async and using await Xrm.WebApi..., or encapsulating the entire process in Promise.all

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

Change the hover effects on the desktop to be more mobile-friendly

In my desktop version, I have implemented some code that enables hovering over a button to display additional information or text. How can I modify this for mobile so that nothing happens when the button is tapped on? .credit:hover .credit-text, .credit- ...

Take out a randomly chosen array from a collection while iterating through it

Currently, I'm delving into the creation of a simulation game inspired by Counter Strike for both entertainment and educational purposes. My Progress: I've meticulously established player objects, organized them into arrays based on their respec ...

Develop interactive, reusable custom modals using React.js

I am currently working on creating a reusable modal: Here is my component setup: class OverleyModal extends Component { constructor(props) { super(props); } openModal = () => { document.getElementById("myOverlay").style.display = "blo ...

Tips for effectively utilizing props in react

Within one of my components named header, there is a button that I want to use to toggle the visibility of the navbar component. To achieve this, I attempted to create a prop in the main component below which houses all the other components including heade ...

Utilize the identical mathematical equation across various jQuery values

I have a JavaScript code that calculates the size of circles on the screen based on multiple variables. Currently, I am repeating the same equation for each circle by numbering all the variables accordingly. Is there a way to simplify this process and run ...

What is the best way to handle multiple promises when loading a state in Angular?

When loading the /home state, I need to retrieve all users from the database in order to customize the home controller and view based on the logged-in user. Currently, in the :resolve section of the state configuration, I am fetching all 'posts' ...

Upgrade angular-chart.js when applied to a filtered collection

I recently started working with Angular and encountered an issue while incorporating Angular Charts JS. I have a list that can be filtered using search text, and I want my charts to update whenever the list is filtered. What would be the best approach to ...

Experiencing issues with obtaining req.params.id undefined while initiating a put request

Encountering an issue while making a PUT request using Postman, as an error occurs in the VSCode terminal with the message: let product = await Product.findById(req.params.id); ^ TypeError: Cannot read property 'id' of undefined. The request ...

React returns Not a Number when summing up numbers

On the cart page, I am calculating the total for each product. Each object contains quantity and price which are multiplied to get the total value of the product. However, since users can have multiple products in their cart, I need to sum the totals of ...

What is the best way to generate a unique bootstrap card for every piece of submitted data?

I am trying to figure out how I can create a dynamic bootstrap card for each submitted data. When the form is submitted, a new card will be created and the data will be stored in that card. Each piece of data will be displayed in a column format similar to ...

How can we delete a specific word from a string if it is found in an

Facing a seemingly simple problem that's proving tricky to solve. I have an array of product names and a sentence. The goal is to remove any product names from the sentence if they appear in it. const products = ["premium t-shirt", "t-shirt", "swea ...

How to access nested JSON elements in Javascript without relying on the eval function

Below is a JSON that I am trying to access. { "orders": { "errorData": { "errors": { "error": [ { "code": "ERROR_01", "description": "API service is down" } ] } }, "status": " ...

Establish a timeout period when using the hover function

My dynamically loaded content requires a specific method of invocation due to its unique nature. While the process runs smoothly without using a setTimeout, is there any way to introduce a 0.25 second delay in this scenario? Check out this fiddle for ref ...

When Mui Select is used with grouping, it automatically selects the first option as the default

When Mui Select with grouping is first rendered, it automatically selects the first option, which may seem strange. const generateOptions = useCallback((options: ISelectOption[]) => { return options.map((opt, ind) => { if ...

Learn how to display months on a countdown timer and then customize the format with basic JavaScript for a website

Looking to create a countdown page for the upcoming ICC cricket world cup event that displays the remaining days in two different formats: Format #1: 01 months 10 days 10 hours Format 2: 01 hours 20 minutes 10 seconds (If less than 2 days remain) I curr ...

How can I use Jquery to animate an element to the right edge of the window?

Exploring the realm of jQuery animations, I am currently experimenting with animating a div to the right side of the window while changing its color using jQuery UI. This is just a fun project without any specific purpose in mind. Below is the code snippet ...

Tips for transferring information from ng-view to the navbar on the index.html page using AngularJS

Recently, I embarked on a journey to learn the MEAN stack and decided to challenge myself by building an authentication page from scratch instead of using the out-of-the-box solution. My main struggle lies in updating texts on my navbar. Here's a snip ...

Using jQuery to target the td:nth-child selector inside a document.ready function is not viable

Currently, I am working on a language learning project where I import a table of German words and their English translations from a .csv file using the jQuery.csvToTable plugin. My goal is to replace the words in the cells with an HTML input when the lang ...

Tips for showing a portion of a string and adding ellipses if it exceeds a certain length

I'm currently using the .map function to display descriptions. I want only 35 characters to be shown, followed by "..." if it exceeds that length. For example: This is a description of thirty five ... This is what I'm trying to achieve: <div ...

Executing a curl POST request within an npm script

I recently added a new script to my npm scripts in the package.json file, but I'm running into issues due to the single and double quotes. The problem seems to be with the internal double quotes within the payload. "slack": "curl -X POST --data-urlen ...