The array is filled with values, however, there seems to be an issue preventing their access. What could possibly be causing this obstacle

After receiving two string values through a callback function, let's call them a and b, I attempt to store them in an array. However, when I check the array using console.log, it only displays the values if I expand the array by clicking on the arrow symbol. Additionally, when I try to access the values by index, it shows up as undefined. It seems like there might be an issue with the function call?

funcOuter() {
    let newList =[];
    this.calledFunc(function (param) {
        newList.push(param);
    });
    console.log(newList[1]);
}

Current Output:

undefined

Expected Output:

123.234.556

Answer №1

When using Angular 2+, incorporating a callback function can be a viable solution to certain challenges.

class AchievementComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  async outerFunction() {
    let newList =[];
    const param = await this.innerFunction();
    newList.push(param);
  }

  innerFunction() {
    return new Promise((resolve, reject)=>{
      this.calledFunction((param)=>{
         resolve(param);
      })
    })
  }

}

Answer №2

It's crucial to visualize the execution of the code:

Stack S

Heap H

Queue Q

When your funcOuter is executed, it goes on the S stack

Along with the assignment, function call, and log:

S: funcOuter, let newList =[];

Assignment is carried out ...

S: funcOuter, this.calledFunc(callback);

The function is executed ...

S: funcOuter, this.calledFunc(callback);, calledFunc inner block

Inner block and async tasks are completed

S: funcOuter, console.log(newList[1]),

Q: possible async calls

The log statement is executed:

S: funcOuter,

Q: possible async calls

The outer function is completed:

S:

Q: possible async calls

The stack is filled from the queue:

S: callback,

Q: possibly more async calls

The push operation is executed:

S: callback, push

And so on ;) Event Loop

Therefore, modify your code to:

funcOuter() {
    let newList =[];
    this.calledFunc(function (param) {
        newList.push(param);
        newList[1] && console.log(newList[1]);
    });

}

This should give you the expected outcomes.

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

PHP file secured to only accept variables posted from HTML form

This is a basic HTML/AJAX/PHP script I have implemented. <form id="new_user" action="" method="post"> <div class="col-md-3 form-group"> <label for="username">Username</label> <input type="text" class="form-control" name ...

Prevent clicking through slides on React by disabling the Swiper feature

Is there a way to handle the global document click event (using React hook useClickAway) so that it still fires even when clicking on a slide? For example, think of a circle in the header like an avatar dropdown - when you click on it, a menu pops up. Th ...

Exploring the power of AngularJS in manipulating Google Maps polygons with the help of ng-repeat

I recently started using a Google Maps plugin specifically designed for AngularJS, which can be found at . My goal is to display polygons on the map, so my HTML code looks something like this: <google-map center="map.center" zoom="map.zoom" draggab ...

The console experienced a forced reflow when a tooltip appeared on the slider handle while executing JavaScript

I am currently facing an issue with my web page that includes various elements along with the Ant.design slider. The values of the slider are being controlled through React states. However, I have noticed that when the slider tooltip is enabled, the respon ...

I'm stumped trying to understand why I keep getting this syntax error. Any thoughts on how to fix it?

Our team is currently working on creating a dynamic SELECT box with autocomplete functionality, inspired by the Standard Select found at this link: We encountered an issue where the SELECT box was not populating as expected. After further investigation, ...

Error: The function of forEach is not applicable to todoList

_serilizedList(todoList){ let serialized = '*My to-dos:*\n'; todoList.forEach((t, i)=> { serialized += '*${i}* - ${t}\n'; }); return serialized; } Unexpected TypeError: todoList.forEach is not ...

Ways to identify modifications from a BehaviorSubject and automatically trigger a response according to the updated value

I am currently implementing a BehaviorSubject for managing languages in my Angular project. I am also utilizing Angular Datatables and trying to dynamically change the language displayed in the data table based on the value returned from the subscription. ...

"Enhancing Collaboration with NextJs Multi-Zones' Unified Header

Currently, I have two applications named admin-shell and delivery-management, both of which are being managed using Multi Zones in NextJs. These applications share a common header with navigation links, but I am encountering difficulties navigating betwee ...

Reasons for aligning inline elements with input boxes

I am facing a challenge with aligning a series of inline elements, each containing an input text box, within a single row. The number and labels of these input boxes can vary as they are dynamically loaded via AJAX. The width of the div housing these inli ...

What is the best way to initiate a Post/Get Request to NodeJS without causing a page refresh?

Struggling to run a NodeJS function after clicking a button? You're not alone. Ajax requests haven't been working for me either when it comes to running NodeJS functions. I've got a bash script that generates a JSON file which I want to par ...

Utilizing local images in Angular with route navigation

I am new to Angular and currently learning about routes, but I have encountered a problem. In my application, I have defined the following routes. However, when trying to link to an image in the assets folder, I receive an error stating that there is no r ...

Having trouble getting code hints to function properly with the official TypeScript plugin on Sublime Text 3

I am experiencing issues with getting code hinting to work using the official TypeScript plugin for Sublime Text 3 on Mac OSX 10.10.5 with Sublime 3. Despite installing it in the packages directory, I am unable to see any code hints. In accordance with th ...

Incorporating database coordinates into Marker React Leaflet: A Step-by-Step Guide

When I retrieve coordinates from the database, they are structured as "lat" and "lon" fields. In my mapping application, I have multiple markers to display. How can I combine these two fields to pass coordinates (coord.lat and coord.lon) to the Marker comp ...

Properly segmenting sections into components in Angular

My project has a specific folder structure as shown below: https://i.sstatic.net/7oihC.png In my list-page, I perform operations such as create, update, and delete using modal dialogs. I am considering creating 4 pages for each of these CRUD operations a ...

Exploring the Integration of the pg Node Package with Angular

Situation As someone new to Angular, I have been working on projects by following tutorials. This has prompted me to start my own project to practice my skills in Angular and Postgres. My goal is to create a web application that connects to a Postgres da ...

The Power of jQuery's .ajax() Utility

I'm a beginner with the jQuery AJAX ajax() Method and have recently created the AddATeacher() function. The function gets called successfully as I see all the alert messages popping up. However, the ajax() Method within the function is not working. Th ...

successful callback after passport registration

router.post('/register', function(req, res, next){ var name = req.body.name; var email = req.body.email; var username = req.body.username; var password = req.body.password; var password2 ...

Encountering 404 Error in Production with NextJS Dynamic Routes

I'm currently working on a next.js project that includes a dynamic routes page. Rather than fetching projects, I simply import data from a local JSON file. While this setup works well during development, I encounter a 404 error for non-existent pages ...

Maximizing the potential of $urlRouterProvider.otherwise in angular js

I am encountering an issue with redirecting to the login screen when there is no UABGlobalAdminId in my storage. I have tried using $urlRouterProvider.otherwise but it doesn't seem to be functioning properly. When I attempt to debug, the console does ...

Wordpress team exhibition

Does anyone know how to create a Team showcase slider in Wordpress? I have been using slick slider, but I'm looking for a way to add team members easily through a plugin rather than manually. I found an image of what I want it to look like. Can any ...