Incredibly peculiar actions exhibited by a coffeescript/javascript array of functions

Something strange is happening with my code in Chrome, creating a mysterious quantum duel state where functions turn into undefined when pushed to an array... eerie!

I am constructing an array of functions using the code below to chain them together for callbacks: https://gist.github.com/3609831

console.log "creating stack"

ids = (id for id of @s3) # an array of integers

stack = [callback]
console.log stack

for ssid of @s3
  new_func =  ((cb) => @idb.load_s3(ssids.shift(),cb))
  console.log new_func
  stack.push new_func
  console.log stack

console.log "stack done"

Although it appears to be functioning correctly - all function calls with the correct arguments are being executed, there's also this odd output in the console:

> creating stack

# callback added to array correctly
> [function () { return _this.start(true); }]

# function generated correctly
> function (cb) { return _this.idb.load_s3(ssids.shift(), cb); } 

# but the function doesn't get added to the array !!!!!!!
> [function () { return _this.start(true); }, undefined × 1]

> stack done

# and the undefined from the array can't be executed of course, verified my line number
> Uncaught TypeError: undefined is not a function 

This indicates that although it worked, it also didn’t work because new_func becomes undefined once pushed to the array...

Strange right?

Anyone have any insights or clues on what might be causing this issue?

I'm using chrome v21

...

EDIT: Just to clarify, the @idb.load_s3 function IS in scope and functioning properly as it loads data from indexedDB and the callback does trigger.

...

EDIT2: Here is the javascript version which looks less readable but essentially mirrors the original code:

var id, ids, new_func, ssid, stack,
  _this = this;

console.log("creating stack");

ids = (function() {
  var _results;
  _results = [];
  for (id in this.s3) {
    _results.push(id);
  }
  return _results;
}).call(this);

stack = [callback];

console.log(stack);

for (ssid in this.s3) {
  new_func = (function(cb) {
    return _this.idb.load_s3(ssids.shift(), cb);
  });
  console.log(new_func);
  stack.push(new_func);
  console.log(stack);
}

console.log("stack done");

...

EDIT 3: It seems like part of the issue may stem from Chrome's asynchronous console behavior. The last item in the stack gets popped off after the console.log but before it actually displays the array contents. As long as I don't execute the function to run the stack, everything seems to function properly.

However, this still doesn't explain the exception related to undefined not being a function, making it all the more peculiar!

...

EDIT #4: load_s3 function can be found here: https://github.com/gnatters/neuroanatomist/blob/master/app/assets/jax/models/asset_loader.js.coffee.erb#L118 The actual code in question is in the same file under load_everything at #L145

Answer №1

After some careful thought, I managed to figure it out! The problem actually had two parts that appeared very similar at first glance. Initially, it seemed like there was an undefined item in the array where the function was pushed, but upon further investigation, it turned out to be a quirk or bug in Chrome's asynchronous console. This led to the function being removed from the array between the console.log call and the actual logging of the array.

The second part of the issue was equally misleading, and I admit I underestimated its significance when posing the question. In the mentioned gist (which has since been updated), the function attempted to pop and execute an additional function from the array, resulting in attempting to call undefined. It was definitely a tricky one to catch...

Everything is now resolved. Thanks for participating ;)

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 it possible to use ajax to display the combination of multiple strings?

In my code, I have a span containing some text. By default, the <span class="switcher__result"> has a CSS property of display: none. However, when my <button class="switcher switcher__Last collapsible"> changes the text, the result span switche ...

Utilizing multiple conditions in MongoDB is a great way to filter results when a specific key

const filterCriteria = { carColor: req.query.carColor, languages: { $regex: `${req.query.languages}`, $options: 'i' }, incomeMonth: { $gte: req.query.incomeMonth }, incomeYear: { $gte: req.query.incomeYear }, ...

jquery interval randomly selecting a new option instead of verifying the correct answer

Below is a jQuery game created with aspx that runs on a 3000 millisecond interval. $(document).ready(function () { var interval; //initialize timer interval = setInterval(function () { //create timer ...

Updating the output without the need for a page refresh following the insertion of data into the database

I'm interested in enhancing the interactivity of this section in my code. Currently, I utilize a form to send announcements via ajax to a php file which successfully updates my database. The table displays the data effectively. However, I want these c ...

Programmatically adding route resolve in Angular using $routeProvider

Is it possible to dynamically add Angular's resolve after it has been initially defined in the app? Let's say we have a setup with routes like this: app.config(['$routeProvider', function ($routeProvider) { $routeProvider ...

What is the best way to allow all authenticated routes to display the Devise ajax Login form?

I have successfully incorporated Devise to accept Ajax Login and have designed a form for logging in via ajax, displayed within a modal. However, I am only able to view the form and login when I set up event binders for specific buttons that activate the m ...

Autofill functions may not be compatible with input fields generated using JavaScript

Having trouble with browsers not using autocomplete in login overlays generated with JavaScript? It can be really annoying. Any suggestions on how to fix this issue? Should I create a hidden form within the original HTML and then move it into the overlay? ...

Make TypeScript parameter optional if it is not supplied

I am working with an interface that defines scenes and their parameters: export interface IScene<R extends string> { path: R; params?: SceneParams; } The SceneParams interface looks like this: export interface SceneParams { [key: string]: s ...

What methods can I use to compare a React Component across multiple pages with Cypress?

One task I am trying to tackle is comparing a component on one page with the same component on another page using Cypress. For example, let's say I have a Pricing Component on the Home page, and I want to verify if the values on the Pricing Page are i ...

Having trouble displaying information in a table using React JS

I devised a feature to display one column of a table and one column for checkboxes (each row should have a checkbox). I stored this file in a component folder with the intention of creating a page where the user selects an account type, and then a new tabl ...

jQuery enables the creation of fresh form fields

Currently, I am working on a form that initially consists of 2 text input fields. The typical use case involves the user entering a number in one field and their name in the other. Following this, the page updates itself without reloading. However, there a ...

What is the correct way to declare and use the useState hook in React?

I am currently working with TypeScript interfaces and the useState hook, attempting to properly type them. However, I encountered an error when comparing a prop variable with a useState variable. The error message states that This comparison appears to be ...

Unable to align span vertically using font-style "Luckiest Guy" in CSS

I have encountered an issue with vertically centering a span using the font-style "Luckiest Guy". https://i.sstatic.net/Lz8o3.png I attempted to use display: flex;align-items: center; on the span, but it did not work. App.vue <template> <div ...

Utilize the same variable within a React functional component across multiple components

Within a React functional component, I am utilizing the following constant: const superHeroPowers = [ { name: 'Superman', status: superManPowerList }, { name: 'Batman', status: batmanPowerList }, { name: 'Wonder Woman&a ...

Rails MultiSelect Array not converting to String Correctly

I am having trouble converting my array to a string properly. I am using rails multiselect: Views: <%= f.select :foo, [ ['a'], ['b'], ['c'] ], {:prompt => "Select an alpha"}, {:multiple => true} %> Controller: ...

Remove the class from all child elements and apply the class to the parent or ancestor of the element that was clicked on using

The Goal: I aim to achieve the following outcome. Whenever a user clicks on any of the radio inputs within the div that has the class corp-struct, I want to assign the following class to the parent element two levels up. This means that, in the example bel ...

Extending functionalities of the "socket" object in the "websockets/ws" library in JavaScript

Any assistance with this matter would be greatly appreciated! Situation: Working on a Node.js-based website incorporating WebSockets, utilizing the websockets/ws library. Objective: Seeking to streamline socket message handling by creating encapsulated " ...

Trigger an event prior to the loading of a div

I have been working on a jQuery code that needs to run just before a specific div is displayed on the page. Take a look at the snippet below as an example of what I am trying to achieve: $(document).ready(function(){ $('.article').on('m ...

What could be the reason for my form submission redirecting to the PHP page?

(I recently discovered that I could edit and reopen the post I had previously made. Feeling a bit confused about the process...) After submitting the form, the email is sent successfully, but then I am redirected to my php page displaying the number 0. Th ...

AFRAME - Enhanced scene overlay

I am currently exploring ways to implement an overlay menu on top of an A-FRAME scene. A great example of what I am aiming for can be found on this website -> By clicking on one of the tiles in the home menu, you will see that the previous scene is mo ...